listview单元格未使用数据绑定进行更新
我绑定了项目源和数据。数据确实发生了变化,但UI没有反映这些变化 我注意到每当调用listview单元格未使用数据绑定进行更新,listview,xamarin,data-binding,xamarin.forms,listviewitem,Listview,Xamarin,Data Binding,Xamarin.forms,Listviewitem,我绑定了项目源和数据。数据确实发生了变化,但UI没有反映这些变化 我注意到每当调用TestUpdateCell时,SetProperty(ref items,value)也不会被调用。但是如果我在TestUpdateCell的末尾添加以下语句: var temp = Items; Items = new List<Item>(); Items = temp; 问题:项目类别: public class Item : MvvmHelpers.ObservableObject
TestUpdateCell
时,SetProperty(ref items,value)
也不会被调用。但是如果我在TestUpdateCell
的末尾添加以下语句:
var temp = Items;
Items = new List<Item>();
Items = temp;
问题:项目类别:
public class Item : MvvmHelpers.ObservableObject
{
public string Name { get; set; }
}
项目数据类:
public class ItemData : List<Item>
{
public ItemData()
{
Add(new Item
{
Name = "Item One"
});
Add(new Item
{
Name = "Item Two"
});
Add(new Item
{
Name = "Item Three"
});
}
}
itempage.XAML:
ListView
ItemsSource="{Binding Items}"
ItemTapped="ItemTapped" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<view:MyItemView/>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView
ListView
ItemsSource=“{Binding Items}”
itemtrapped=“itemtrapped”>
如果我没看错的话,您现在已经在带有项的列表上实现了属性更改机制。当您要更改项目中的值时
在项
类中实现已更改的属性
如果要动态添加和删除单元格,请将它们放入可观察集合中。但再一次;重要的是要注意这里;这只是观察列表本身的变化,而不是列表项内部的变化。使用ObservableCollection代替列表谢谢,这就是我所缺少的。
public class ItemViewModel : MvvmHelpers.BaseViewModel
{
public ItemViewModel()
{
Items = new ItemData();
}
List<Item> items;
public List<Item> Items
{
get { return items; }
set { SetProperty(ref items, value); }
}
public void TestUpdateCell()
{
Items[0].Name = "Item One Updated";
}
}
public class ItemPage : ContentPage
{
ItemViewModel ivm;
public ItemPage()
{
BindingContext = ivm = new ItemViewModel();
}
void ItemTapped(object sender, ItemTappedEventArgs e)
{
ivm.TestUpdateCell();
}
}
ListView
ItemsSource="{Binding Items}"
ItemTapped="ItemTapped" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<view:MyItemView/>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView
<ContentView
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MyProject;assembly=MyProject"
x:Class="MyProject.MyItemView">
<local:CardFrame
IsClippedToBounds="True"
HasShadow="True" >
<StackLayout
Spacing="0"
Orientation="Horizontal">
<Grid
RowSpacing="0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<local:MyLabel
Grid.Row="0"
Grid.Column="0"
Grid.ColumnSpan="4"
FontSize="18"
FontAttributes="Bold"
Text="{Binding Name}"/>
<!-- omitted rows and columns -->
</Grid>
</StackLayout>
</local:CardFrame>
</ContentView>