【问题标题】:How to convert my ListView binding to x:Bind?如何将我的 ListView 绑定转换为 x:Bind?
【发布时间】:2019-03-14 17:09:21
【问题描述】:

假设我在我的应用中指定了以下示例数据源:

App.xaml:

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

如何将以下两个绑定转换为它们的 x:Bind 变体???

UsersPage.xaml.

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

【问题讨论】:

    标签: xaml uwp uwp-xaml xbind


    【解决方案1】:
    1. UsersPage.xaml 的代码隐藏中公开SampleUsers

      public SampleUsers SampleUsers => new SampleUsers();
      
    2. 在 XAML 中使用 {x:Bind} 绑定到它:

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

    {x:Bind} 不使用DataContext 作为默认源,而是使用official docs 中所述的页面或用户控件本身。另请注意,默认模式是OneTime,假设您在运行时不重置源属性,在这种情况下非常好。

    【讨论】:

      【解决方案2】:

      如果你想使用 x:bind,你可以绑定 ItemsSource 然后为 DataTemplate 声明 x:DataType,如下所示。

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

      更新

      您可以在 xaml 页面资源或代码中定义 SampleUsers

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

      更多详情请参考document

      【讨论】:

      • 没有用,它给出了错误:当我将 ItemsSource 绑定更改为您的答案时,在“UsersPage”类型中找不到“属性 SampleUsers”。
      • 除非我有误解,否则 x:Bind 只会看到页面范围内的属性,而不是 App.xaml 中的属性?这就是它不起作用的原因吗?
      • @Maximus,我已经更新了案例回复,有用吗?
      猜你喜欢
      • 2016-11-26
      • 2015-08-19
      • 2017-08-06
      • 1970-01-01
      • 1970-01-01
      • 2016-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多