Maximus
Maximus

Reputation: 1299

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}" />

Upvotes: 0

Views: 115

Answers (2)

Nico Zhu
Nico Zhu

Reputation: 32775

If you want to use x:bind, you could bind ItemsSource then declarex x:DataType for DataTemplate like the following.

<ListView  ItemsSource="{x:Bind SampleUsers.Users, Mode=OneWay}" >
    <ListView.ItemTemplate>
        <DataTemplate x:DataType="local:User">
            <TextBlock Text="{x:Bind Name}"
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Update

You could define the SampleUsers in xaml page resource or code behind.

<Page.Resources>
    <sampleData:SampleUsers x:Key="SampleUsers"/>
</Page.Resources>

For more detail please refer this document.

Upvotes: 1

mm8
mm8

Reputation: 169150

  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.

Upvotes: 2

Related Questions