Some of you likely want to start using XAML but your desktop projects also run on macOS and perhaps Linux. If that’s the case, what do you do to use XAML for Windows? What you can’t do is simply drag a DesktopXAMLContainer onto the layout and expect the compiler to ignore it when you build for macOS and Linux. That won’t work. But fear not. There is a solution!
You can add a subclass of DesktopXAMLContainer to your project then create an instance of it at runtime when your project compiles for Windows. I created an example project that is available now (thanks to the fact that Xojo now loads examples over the Internet). It’s called ChameleonControls and you can find it by going to the Project Chooser, clicking on Examples then going to Platforms > Desktop > Windows > XAMLContainer > ChameleonControls.
The example project explains how it works but essentially you:
- Add a subclass to your project setting its Super to DesktopXAMLContainer.
- In its Opening event or the Constructor method, set the Content property to the appropriate XAML to create the control you want. You can get this by dragging a DesktopXAMLContainer to a layout, then clicking the Pencil, choosing the control you want and copying the contents of the Content property from the Inspector.
- Next you add a property of the type of the subclass you created to the window. In the example, the subclass is called ToggleSwitch (because that’s the type of XAML control it creates) so the property on the window is MyToggleSwitch As ToggleSwitch.
- Using conditional compilation, in the code of the Opening event of the control you wish to swap out on Windows, you hide the control then create an instance of your subclass, setting it’s Left and Top to the same values as the control on the window.
- In Build Settings > Windows > Advanced, set the Use WinUI (Experimental) option to ON. When you run, the control on your layout is hidden and the XAML control appears.
Download the example project and check it out.
Got ideas for examples you’d like to see us add or topics for blog posts? Contact us.