通常,您不会直接触摸您的细胞。相反,如果可能,您会尝试通过数据绑定来完成所有事情。
让我们使用 XAML 中定义的以下页面:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="App6.Page1">
<ListView x:Name="myList"
BackgroundColor="Gray"
ItemsSource="{Binding MyItems}"
HasUnevenRows="true"
RowHeight="-1">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<StackLayout
HorizontalOptions="FillAndExpand"
VerticalOptions="StartAndExpand"
Padding="15, 10, 10, 10"
BackgroundColor="White">
<Label Text="{Binding Title}"
FontSize="18"
TextColor="Black"
VerticalOptions="StartAndExpand"/>
</StackLayout>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage>
在您的 Page 中,您将 ViewModel 设置为 BindingContext。
public partial class Page1 : ContentPage
{
public Page1()
{
InitializeComponent();
BindingContext = new Page1ViewModel();
}
}
并且您的 ViewModel 在 ObservableCollection 中包含您的 Items MyItems,这意味着如果您添加或删除 Items,您的视图会更新。此属性绑定为您 List 的 ItemsSource(请参阅 XAML:ItemsSource="{Binding MyItems}")。
class Page1ViewModel : INotifyPropertyChanged
{
private ObservableCollection<MyItem> _myItems = new ObservableCollection<MyItem>();
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<MyItem> MyItems
{
get { return _myItems; }
set
{
_myItems = value;
OnPropertyChanged();
}
}
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public Page1ViewModel()
{
MyItems.Add(new MyItem { Title = "Test" });
MyItems.Add(new MyItem { Title = "Test2" });
MyItems.Add(new MyItem { Title = "Test3" });
MyItems.Add(new MyItem { Title = "Test4" });
MyItems.Add(new MyItem { Title = "Test5" });
}
public void ChangeItem()
{
MyItems[1].Title = "Hello World";
}
}
对于每个项目,您都有一个代表一个单元格数据的对象。此项的类型实现INotifyPropertyChanged。这意味着,它会通知已更改的属性。数据绑定机制注册到此事件,并在引发时更新视图。
public class MyItem : INotifyPropertyChanged
{
private string _title;
public string Title
{
get { return _title; }
set
{
_title = value;
OnPropertyChanged(); // Notify, that Title has been changed
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
如果您现在更改其中一项,例如致电ChangeItem()。然后第二个单元格的标签将更新为"Hello World",因为它绑定到标题(请参阅 XAML Text="{Binding Title}")。
这一切背后的一般思想称为 MvvM 模式,您希望将视图与视图逻辑和模型(数据/服务,...)分开。