加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 替换ObservableCollection时ListView不更新

发布时间:2020-12-16 01:56:59 所属栏目:百科 来源:网络整理
导读:我无法理解为什么在替换ObservableCollection(使用新的)并且未更改(添加或删除的项目)时不会刷新ListView. 我尊重属性通知的所有要求,因为我正在为我的视图模型使用DependencyObject,并且在替换集合时调用SetValue. 我有一个WPF ListView绑定到我的视图模型
我无法理解为什么在替换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" 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引用?为什么?

解决方法

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

public static readonly DependencyProperty ColProperty =
    DependencyProperty.Register("Col",new PropertyMetadata(null));

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读