替换ObservableCollection时ListView未更新

本文关键字:更新 ListView ObservableCollection 替换 | 更新日期: 2023-09-27 18:29:04

我不明白为什么当ObservableCollection被替换(用新的)而没有更改(添加或删除项)时,ListView没有刷新。我尊重属性通知的所有要求,因为我使用DependencyObject作为视图模型,并且在替换集合时会调用SetValue。

我有一个WPF ListView绑定到我的视图模型的Col属性:

public class ViewModel1 : DependencyObject
{
    public ViewModel1()
    {
        Col = new ObservableCollection<string>(new[] { "A", "B", "C", "D" });
    }
    protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
    {
        base.OnPropertyChanged(e);
        Debug.WriteLine("Property changed "+ e.Property.Name);
    }   
    public ObservableCollection<string> Col
    {
        get { return (ObservableCollection<string>)GetValue(ColProperty); }
        set { SetValue(ColProperty, value); }
    }
    // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ColProperty =
        DependencyProperty.Register("ColProperty", typeof(ObservableCollection<string>), typeof(ViewModel1), new PropertyMetadata(null));
}

XAML类似于:

<Window x:Class="BindingPOC.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 Margin="0,10,0,0" ItemsSource="{Binding Col}" />
            <Button Click="Button_Click" >click</Button>
        </StackPanel>
    </Grid>
</Window>

因此,有了这段代码,如果我不替换最初的ObservableCollection,一切都会很好。但当我点击按钮时。我将列表替换为:

 private void Button_Click(object sender, RoutedEventArgs e)
        {
            (DataContext as ViewModel1).Col = new System.Collections.ObjectModel.ObservableCollection<string>(new[] { "Z", "ZZ" });
        }

为Col调用了视图模型上的PropertyChanged方法,但ListView没有更新其内容。

我需要保存相同的ObservableCollection引用吗?为什么?

替换ObservableCollection时ListView未更新

这是因为您的依赖属性注册不正确。传递给Register方法的属性名称应为"Col",而不是"ColProperty":

public static readonly DependencyProperty ColProperty =
    DependencyProperty.Register("Col", typeof(ObservableCollection<string>), typeof(ViewModel1), new PropertyMetadata(null));

初始绑定之所以有效,是因为有一个名为Col的属性,但它未被检测为依赖属性,因此绑定不会自动更新。