我对数据绑定的概念非常陌生,我不认为我完全理解它。我有一个名为Project
的类,其中包含一个类型为ToDo
的LinkedList
作为其属性之一。当我导航到Project
的一个实例时,我将在ListView
中显示ToDo
类型的LinkedList
。我创建了函数,允许我更改LinkedList
中节点的顺序(向上移动、向下移动)并删除所选节点。我希望每当LinkedList
发生更改(向上移动、向下移动或删除)时,ListView
都会刷新。然而,我无法做到这一点。以下是我的代码:(未包括所有部分)
页面的XAML:
<ListView x:Name="myListView" ItemsSource="{Binding Source={StaticResource ToDos}, Mode=TwoWay}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<CheckBox x:Name="myCheckBox"
Content="{Binding ToDoTitle, Mode=TwoWay}"
IsChecked="{Binding IsCompleted, Mode=TwoWay}">
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
C# 数据模型:
public class ToDo : INotifyPropertyChanged
{
private string toDoTitle;
private bool isCompleted;
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public string ToDoTitle { get { return this.toDoTitle; } set { this.toDoTitle = value; this.OnPropertyChanged(); } }
public bool IsCompleted { get { return this.isCompleted; } set { this.isCompleted = value; this.OnPropertyChanged(); } }
public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
// Raise the PropertyChanged event, passing the name of the property whose value has changed.
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public class Projects : INotifyPropertyChanged
{
private LinkedList<ToDo> toDos;
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public LinkedList<ToDo> ToDos { get { return this.toDos; } set { this.toDos = value; this.OnCollectionChanged(); } }
public Projects()
{
ToDos = new LinkedList<ToDo>();
}
public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
// Raise the PropertyChanged event, passing the name of the property whose value has changed.
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
谢谢。
ObservableCollection<ToDo>
替换LinkedList<ToDo>
。它实现了与INotifyPropertyChanged
类似的接口:INotifyCollectionChanged。 - Manfred Radlwimmer