WPF如何从DataGrid引发单个属性更改绑定到ObservableCollection

时间:2014-04-22 13:58:35

标签: c# wpf xaml observablecollection

问题是,这是怎么做到的?

从DataGrid我可以获得已经绑定到其ItemSource的该集合的SelectedRow,但我真的需要一个setter和getter来处理属于ObservableCollection的单个属性。

例如,我需要在用户检查datagrid中的bool属性时捕获,因此setter将设置为“false / true”。像

这样的东西
    //But the Archive property is in the DataContext of the row item... 
    //so this wouldnt work, I think..

    private bool m_Archived = false;

    public bool Archived
    {
        get { return m_Archived; }
        set
        {
            m_Archived = value;

            OnPropertyChanged("Archived");
        }
    }

但请记住,此属性是ObservableCollection(DataContext)

的一部分

干杯

1 个答案:

答案 0 :(得分:0)

您需要注册已更改的每个集合项属性,然后控制所需属性的更改时间,然后更改已存档的属性。请查看以下示例代码:

private ObservableCollection<TClass> _SomeObservableCollection;

public ObservableCollection<TClass> SomeObservableCollection
{
    get { return _SomeObservableCollection ?? (_SomeObservableCollection = SomeObservableCollectionItems()); }
}

private ObservableCollection<TClass> SomeObservableCollectionItems()
{
    var resultCollection = new ObservableCollection<TClass>();

    foreach (var item in SomeModelCollection)
    {
        var newPoint = new TClass(item) {IsLocated = true};
        newPoint.PropertyChanged += OnItemPropertyChanged;
        resultCollection.Add(newPoint);
    }

    resultCollection.CollectionChanged += OnSomeObservableCollectionCollectionChanged;

    return resultCollection;
}

private void OnSomeObservableCollectionCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    if (e.NewItems != null)
    {
        foreach (TClass TClass in e.NewItems)
        {
            TClass.PropertyChanged += OnItemPropertyChanged;
        }
    }
    if (e.OldItems != null)
    {
        foreach (TClass TClass in e.OldItems)
        {
            TClass.PropertyChanged -= OnItemPropertyChanged;
        }
    }
    if (!Patient.HasChanges)
        Patient.HasChanges = true;
}


private void OnItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if (e.PropertyName != "ItemArchivedProperty") return;
    // set Archived = true or set Archived = false 
}

这只是一个例子,但它应该有效。希望它有所帮助。