WPF How to raise an Individual property change from DataGrid bounded to a ObservableCollection

StackOverflow https://stackoverflow.com/questions/23221713

質問

As the question ask, how is this done ?

From a DataGrid I can get the SelectedRow of that collection that has been bounded to its ItemSource, but I really need a setter and getter for an individual property that belongs inside the ObservableCollection.

For example, I need to catch when a user checks a bool property inside a datagrid, so then the setter would be set to "false/true". So something like

    //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");
        }
    }

But remember this property is part of the ObservableCollection (DataContext)

Cheers

役に立ちましたか?

解決

You need to register to each collection item property changed, then to control when the desired property has changed, then change the archived property. Check this sample code:

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 
}

This is just an example, but it should works. Hope it helps.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top