WinUI Stuff: accessing the properties of another control (named element) using x:bind

x:bind is a quite powerful command and feature in XAML. You can get the data for your XMAL-control from (almost) anywhere. You can even get it from another control, and you do not write (almost) a single line of code.

Let’s say you have a SplitView and you want to hide/unhide the pane of the SplitView by another control, let’s say by a ToggleSwitch.

You could write for the SplitView:

<SplitView x:Name="MySplitView"
           IsOpen="{x:bind MyToggleSwitch_ForPane.IsOn,
           Mode=OneWay}">
  <SplitView.Pane>
  ...
</SplitView>

Instead of hardcoding, the state of the pane, like IsOpen=“true“ (if the pane is visible) of IsOpen=“false“ (if the pane is hidden), we ask another control – MyToggleSwitch_ForPane – what to do.

We implement the ToggleSwitch and set it initially to „true“ (which means the pane will be visible initially as well):

<ToggleSwitch x:Name="MyToggleSwitch_ForPane" Header="Enable/Disable Pane" IsOn="true"/>

So, the SplitView control uses the IsOn property of the ToggleSwitch to hide/unhide its pane.

You could do the same thing with the SplitView using the binding attribute instead of x:bind:

<SplitView x:Name="MySplitView"
           IsOpen="{binding ElementName=MyToggleSwitch_ForPane
           Path=IsOn, Mode=OneWay}">
  <SplitView.Pane>
  ...
</SplitView>

Personally, I prefer x:bind instead of binding, since it is the stronger binding.

However, using x:bind you might see an error like „MyToggleSwitch_ForPane is not a member of MyPage in line … (where you use the SplitView)“ (assuming, MyPage is the wrapping <Page>). So what happened? As always, nothing is free and therefore, also the using x:bind is „not for free“. Means, you need some additional code. Even though, the error statement is not really helpful (if you don’t know the behinds), it tells the problem: the XAML-interpreter does not know about MyToggleSwitch_ForPane.

If you want to reference named elements using x:bind, they need to declarated in the IDL file:

Windows.UI.Xaml.Controls.ToggleSwitch MyToggleSwitch_ForPane{ get; };

Basically – and this is quite understandable when you’re familiar with XAML – x:bind needs a getter to access the control. There is no need to declare the function in the header file or even to define the function in the .cpp (assuming your code is winrt/C++) file. Same is for the .cs file (assuming your code is winrt/C#).

Where to go from here:

About the IDL, XAML and header file: https://stackoverflow.com/questions/69125714/what-properties-functions-have-to-go-in-an-idl-when-using-xaml-and-c-winrt

About the pros and cons of strong binding using x:bind versus weak binding using binding: https://github.com/microsoft/microsoft-ui-xaml/issues/6411

About binding a control in a XAML file: https://learn.microsoft.com/en-us/windows/uwp/cpp-and-winrt-apis/binding-property

Veröffentlicht in Blog.