如果您将 Campers 设置为指向一个新实例,那么 RaisePropertyChanged 将为您完成这项工作。否则,您将引用旧实例,并且视图将保持不同步。另一个解决方案是,每次将 Campers 设置为指向新集合时,再次为 DataGrid 或 ListView 或您使用的任何控件设置 ItemsSource。
确实,只要您从收藏中添加或删除项目,此方法就有效。总而言之,这就是区别,当你再次设置时
Campers = new ObservableCollection<Camper>();
您的 RaisePropertyChanged 将被触发。
代码更新:
XAML:
<Window x:Class="ObservablePropertyChanged.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel>
<ListView ItemsSource="{Binding items}">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Button Content="Change collection" Click="btnChangeCollection_Click"/>
</StackPanel>
</Grid>
后面的代码:
public partial class MainWindow : Window
{
public ObservableCollection<string> items { get; set; }
public MainWindow()
{
InitializeComponent();
items = new ObservableCollection<string>();
items.Add("One");
items.Add("Two");
this.DataContext = this;
}
private void btnChangeCollection_Click(object sender, RoutedEventArgs e)
{
items = new ObservableCollection<string>();
items.Add("Three");
items.Add("Four");
}
}
由于我没有实现 INPC 接口,并且没有在项目集合上添加 PropertyChanged,因此单击按钮后,您将不会使用项目“三”和“四”更新视图。
这是完成此行为的另一种方法:
public ObservableCollection<string> items
{
get { return (ObservableCollection<string>)GetValue(itemsProperty); }
set { SetValue(itemsProperty, value); }
}
// Using a DependencyProperty as the backing store for items. This enables animation, styling, binding, etc...
public static readonly DependencyProperty itemsProperty =
DependencyProperty.Register("items", typeof(ObservableCollection<string>), typeof(MainWindow), new UIPropertyMetadata(null));
使用此依赖属性,ListView 将保持同步。