3

我不明白为什么当 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 参考?为什么 ?

4

1 回答 1

7

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

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

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

于 2013-08-24T21:40:21.760 回答