Vis*_*uel 6 c# data-binding listview xamarin xamarin.forms
我试图对象的列表绑定到一个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;
Run Code Online (Sandbox Code Playgroud)
MainPage.xaml中:
<ListView x:Name="ListView">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Showing}" TextColor="White"></TextCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Run Code Online (Sandbox Code Playgroud)
虽然列表项是(!),但行中的文本不会显示: 绑定结果
我已经尝试过这个解决方案,结果是一样的:Xamarin ListView没有显示任何数据
我怎样才能做到这一点?似乎绑定不会(完全)使用字段,变量需要是属性!
您需要设置 ItemsSource 将 ObservableCollection 绑定到 ListView
<ListView ItemsSource="{Binding ExampleList}">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Showing}" TextColor="White" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Run Code Online (Sandbox Code Playgroud)
另请记住,使用 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"});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3065 次 |
| 最近记录: |