MVVM/ObservableCollection问题 [英] MVVM / ObservableCollection Question

查看:153
本文介绍了MVVM/ObservableCollection问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下XAML:

   <Grid x:Name="LayoutRoot">
        <sdk:DataGrid AutoGenerateColumns="True" Margin="46,38,0,40" x:Name="FamilyListGrid" HorizontalAlignment="Left" Width="475" 
               ItemsSource="{Binding FamilyList}"
               SelectedItem="{Binding SelectedFamily, Mode=TwoWay}" />
    </Grid>

在Binding中使用的我的FamilyList属性是我的视图模型类中实体的ObservableCollection.我发现我需要在FamilyList集合的setter中实现INotifyPropertyChanged,否则绑定不起作用.据我了解,一个ObservableCollection已经实现了这一点.如果是这种情况,为什么我需要实现notify属性?

My FamilyList property used in the Binding is an ObservableCollection of entities in my view model class. I'm finding that I need to implement INotifyPropertyChanged in the setter of my FamilyList collection or the binding doesn't work. It was my understanding that an ObservableCollection already implemented this. If this is the case, why do I need to implement the notify property?

如果有帮助,这是我的FamilyList属性定义:

If it helps, here is my FamilyList property definition:

    private ObservableCollection<Services.Family> familyList;
    public ObservableCollection<Services.Family> FamilyList
    {
        get { return familyList; }
        private set 
        { 
            familyList = value;
            NotifyPropertyChanged("FamilyList");
        }
    }

推荐答案

ObservableCollection<T>实现INotifyCollectionChanged,该INotifyCollectionChanged通知已注册事件处理程序有关集合中的更改(添加,删除,项目排序).但是,DataGrid必须知道您的业务对象之一的属性是否已更改以更新网格中的值.为此,需要INotifyPropertyChanged.
ObservableCollection<T>也实现INotifyCollectionChanged.但是,仅当集合的属性已更改时,才可以使用此方法进行通知.没有一种机制可以让集合检测您的业务对象是否已更改(如果有的话,它将注册到您的业务对象的INotifyCollectionChanged:).

ObservableCollection<T> implements INotifyCollectionChanged which informs a registered event handler about changes in the collection (add,remove,sort of items). However the DataGrid must know if a property of one of your business-objects has changed to update the value in the grid. For this, INotifyPropertyChanged is needed.
ObservableCollection<T> implements also INotifyCollectionChanged. However this can only be used to be informed if a property of the collection has been changed. There is no mechanism that let the collection detect if your business object has been changed (and if it would have, it would register to INotifyCollectionChanged of your business object :).

这篇关于MVVM/ObservableCollection问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆