xamluwpuwp-xamlxbind

How to convert my ListView binding to x:Bind?


Suppose I have the following source of sample data specified in my app:

App.xaml:

<sampleData:SampleUsers x:Key="SampleUsers"
        d:IsDataSource="True" />

How do I convert the following two bindings to their x:Bind variants ???

UsersPage.xaml.

xmlns:sampleData="using:MyApp.SampleData.SampleUsers"
.
.
.
<ListView DataContext="{Binding Source={StaticResource SampleUsers}}"
        ItemsSource="{Binding Users, Mode=OneWay}" />

Solution

    1. Expose SampleUsers from the code-behind of UsersPage.xaml:

      public SampleUsers SampleUsers => new SampleUsers();
      
    2. Bind to it using {x:Bind} in the XAML:

      <ListView ItemsSource="{x:Bind SampleUsers}" />
      

    {x:Bind} does not use the DataContext as a default source — instead, it uses the page or user control itself as stated in the official docs. Also note that the default mode is OneTime, which is perfectly fine in this case assuming you don't reset the source property during runtime.