简体   繁体   中英

Raising event when Property in ObservableCollection changes

I want to raise an Event when a Property in a DataGrid is changed to check if it is valid, save it back to my source file, etc.

Background Information: I have a DataGrid which is bound to an Observable Collection. At this point I have successfully bound my Observable Collection to the view, however I haven't managed to raise an Event upon Property changes. Two Way binding also works as i could observe changes to the Collection via debugging. I'm inheriting INotifyPropertyChanged through BindableBase(Prism).

public ObservableCollection<CfgData> Cfg
{
    get { return _cfg; }
    set { SetProperty(ref _cfg, value); }
}
private ObservableCollection<CfgData> _cfg;

CfgData contains 4 Properties:

public class CfgData
{
    public string Handle { get; set; }
    public string Address { get; set; }
    public string Value { get; set; }
    public string Description { get; set; }

    public CfgData(string handle, string address, string value)
    {
        this.Handle = handle;
        this.Address = address;
        this.Value = value;
    }

    public CfgData(string handle, string address, string value, string description)
    {
        this.Handle = handle;
        this.Address = address;
        this.Value = value;
        this.Description = description;
    }
}

I am populating my Observable Collection with Values read from a csv. file

public ObservableCollection<CfgData> LoadCfg(string cfgPath)
{
var cfg = new ObservableCollection<CfgData>();
try
{
    using (var reader = new StreamReader(cfgPath))
    {
        while (!reader.EndOfStream)
        {
            var line = reader.ReadLine();
            var values = line.Split(';');

            if (values.Length == 3)
            {
                cfg.Add(new CfgData(values[0], values[1], values[2]));
            }
            else if (values.Length == 4)
            {
                cfg.Add(new CfgData(values[0], values[1], values[2], values[3]));
            }
        }
    }
}
catch (Exception x)
{
    log.Debug(x);
}
return cfg;
}

My XAML

 <DataGrid Name="cfgDataGrid" Margin="10,10,109,168.676" ItemsSource="{Binding Cfg, Mode=TwoWay}" AutoGenerateColumns="False"> <DataGrid.Columns> <DataGridTextColumn Header="Handle" Binding="{Binding Path=Handle}" Width="auto" IsReadOnly="True" /> <DataGridTextColumn Header="Address" Binding="{Binding Path=Address}" Width="auto" IsReadOnly="True" /> <DataGridTextColumn Header="Value" Binding="{Binding Path=Value}" Width="auto" IsReadOnly="False" /> <DataGridTextColumn Header="Description" Binding="{Binding Path=Description}" Width="auto" IsReadOnly="True" /> </DataGrid.Columns> </DataGrid> 

The Problem 2 way binding updates the collection in my viewmodel. However i would like to verify the input before saving it. I would also like to be able to add some functionality like calling a method when an edit is verified. Therefore I have attempted to use several event handling ways like

this.Cfg.CollectionChanged += new NotifyCollectionChangedEventHandler(Cfg_OnCollectionChanged);

or

this.Cfg.CollectionChanged += Cfg_OnCollectionChanged;

however those never called the functions when i changed the datagrid.

The Questions How do i create an event handler that gets called upon a Property change? Do i have to save back the whole set of Data or can i save back just the changed datarow/property?

Because ObservableCollection doesn't observe his items. It will raise an event for an insert, delete an item, or reset the collection, not a modification on his item.

So, you must implement ObservableCollection which observe equally his items. This code used in my project found on SO but I can't figure out the post original. When we add the new item to the collection, it adds an INotifyPropertyChanged event for it.

    public class ItemsChangeObservableCollection<T> :
           System.Collections.ObjectModel.ObservableCollection<T> where T : INotifyPropertyChanged
    {
        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Add)
            {
                RegisterPropertyChanged(e.NewItems);
            }
            else if (e.Action == NotifyCollectionChangedAction.Remove)
            {
                UnRegisterPropertyChanged(e.OldItems);
            }
            else if (e.Action == NotifyCollectionChangedAction.Replace)
            {
                UnRegisterPropertyChanged(e.OldItems);
                RegisterPropertyChanged(e.NewItems);
            }

            base.OnCollectionChanged(e);
        }

        protected override void ClearItems()
        {
            UnRegisterPropertyChanged(this);
            base.ClearItems();
        }

        private void RegisterPropertyChanged(IList items)
        {
            foreach (INotifyPropertyChanged item in items)
            {
                if (item != null)
                {
                    item.PropertyChanged += new PropertyChangedEventHandler(item_PropertyChanged);
                }
            }
        }

        private void UnRegisterPropertyChanged(IList items)
        {
            foreach (INotifyPropertyChanged item in items)
            {
                if (item != null)
                {
                    item.PropertyChanged -= new PropertyChangedEventHandler(item_PropertyChanged);
                }
            }
        }

        private void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            //launch an event Reset with name of property changed
            base.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
        }
    }
}

Next, your model

private ItemsChangeObservableCollection<CfgData> _xx = new ItemsChangeObservableCollection<CfgData>();
public ItemsChangeObservableCollection<CfgData> xx 
{
    get { return _xx ;}
    set { _xx = value; }
}

Last but not least, your model must implement INotifyPropertyChanged

public class CfgData: INotifyPropertyChanged
{

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM