繁体   English   中英

Xamarin.Forms 绑定有效,但文本未显示

[英]Xamarin.Forms Binding works, but text is not showing

很长一段时间以来,我一直试图将对象列表绑定到列表listview ,但是尽管它在我不需要编写 itemtemplate 的列表中按预期工作(例如ObservableCollection<string> ),但它不适用于列表我想要一个项目itembinding到列表中对象的字段:

MainPage.xaml.cs:

ExampleList = new ObservableCollection<ExampleItem>()
{
    new ExampleItem() {Showing = "Item 1"},
    new ExampleItem() {Showing = "Item 2"}
};
ListView.ItemsSource = ExampleList;

主页.xaml:

<ListView x:Name="ListView">
      <ListView.ItemTemplate>
        <DataTemplate>
            <TextCell Text="{Binding Showing}" TextColor="White"></TextCell>
        </DataTemplate>
      </ListView.ItemTemplate>
</ListView>

虽然列表项在那里(!),但行中的文本没有显示:绑定结果

我已经尝试过这个解决方案,结果是一样的: Xamarin ListView 不显示任何数据

答案:似乎绑定不能(完全)与字段一起使用,变量需要是属性

确保 ItemsSource 中的项目实现 INotifyPropertyChanged 并且您绑定到的每个属性的 setter 会触发 PropertyChanged 事件。

除了在 ItmsSource 的属性设置器上触发 PropertyChanged 之外。

您需要设置 ItemsSource 以将 ObservableCollection 绑定到 ListView

<ListView ItemsSource="{Binding ExampleList}">
  <ListView.ItemTemplate>
    <DataTemplate>
      <TextCell Text="{Binding Showing}" TextColor="White" />
    </DataTemplate>
  </ListView.ItemTemplate>
</ListView>

另请记住,在使用 Xamarin.Forms 时,最好遵循 MVVM 模式。 您应该在 ViewModel 类中有 ObservableCollection,并将其设置为 View 上的 BindingContext

编辑:ObservableCollection 似乎调用 OnPropertyChange 来更新 Add 方法上的 UI。 只需在设置 ItemsSource 后将项目添加到集合中。 这应该够了吧

ExampleList = new ObservableCollection<ExampleItem>();
ListView.ItemsSource = ExampleList;

ExampleList.Add(new ExampleItem() {Showing = "Item 1"});
ExampleList.Add(new ExampleItem() {Showing = "Item 2"});

正如评论中所写“绑定不适用于字段,它需要属性”。 我是 xamarin 的新手,我对此很挣扎。 但这是明确的答案。

这个问题是一个老问题,已经得到很好的解决。 但您也可以通过 XAML 设置 ItemSource。 通过做这个:

<ListView x:Name="ListView" ItemsSource="{Binding ExampleList}">
      <ListView.ItemTemplate>
        <DataTemplate>
            <TextCell Text="{Binding Showing}" TextColor="White"></TextCell>
        </DataTemplate>
      </ListView.ItemTemplate>
</ListView>

这可以帮助避免此类问题😉

在此处查看更多信息: https : //docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/listview/data-and-databinding

我希望我以某种方式有用😁

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM