ObservableCollection中的Property更改时引发事件

时间:2018-07-30 10:03:50

标签: c# wpf events datagrid prism

当要更改DataGrid中的属性以检查其是否有效,将其保存回我的源文件等时,我想引发一个事件。

背景信息: 我有一个绑定到Observable集合的DataGrid。 至此,我已经成功将Observable Collection绑定到视图,但是在Property更改时我还没有引发一个Event。 双向绑定也可以工作,因为我可以通过调试观察Collection的更改。 我正在通过BindableBase(Prism)继承INotifyPropertyChanged。

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

CfgData包含4个属性:

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;
    }
}

我正在用从csv读取的值填充我的Observable集合。文件

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;
}

我的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>

问题 2种方式绑定会更新我的视图模型中的集合。但是我想在保存之前验证输入。我还希望能够添加一些功能,例如在验证编辑后调用方法。因此,我尝试使用几种事件处理方式,例如

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

this.Cfg.CollectionChanged += Cfg_OnCollectionChanged;

但是当我更改数据网格时那些从未调用过的函数。

问题 如何创建在属性更改时被调用的事件处理程序?我必须保存整个数据集还是可以只保存更改后的数据行/属性?

1 个答案:

答案 0 :(得分:1)

因为ObservableCollection没有观察他的物品。它将引发插入事件,删除项目或重置集合,而不是对其项目进行修改。

因此,您必须实现ObservableCollection来平等地观察他的项目。我的项目中使用的这段代码可以在SO上找到,但是我无法弄清楚帖子的原件。当我们将新项目添加到集合时,它将为其添加INotifyPropertyChanged事件。

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

接下来,您的模型

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

最后但并非最不重要的是,您的模型必须实现INotifyPropertyChanged

public class CfgData: INotifyPropertyChanged
{

}
相关问题