简体   繁体   English

ObservableCollection中的Property更改时引发事件

[英]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. 我想在更改DataGrid中的属性以检查其是否有效,将其保存回我的源文件等时引发一个事件。

Background Information: I have a DataGrid which is bound to an Observable Collection. 背景信息:我有一个绑定到Observable集合的DataGrid。 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. 至此,我已经成功将Observable Collection绑定到视图,但是在Property更改时我还没有引发一个Event。 Two Way binding also works as i could observe changes to the Collection via debugging. 双向绑定也可以工作,因为我可以通过调试观察Collection的更改。 I'm inheriting INotifyPropertyChanged through BindableBase(Prism). 我正在通过BindableBase(Prism)继承INotifyPropertyChanged。

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

CfgData contains 4 Properties: 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;
    }
}

I am populating my Observable Collection with Values read from a csv. 我正在用从csv读取的值填充我的Observable集合。 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 我的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. 问题 2方式绑定更新了我的视图模型中的集合。 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. 因为ObservableCollection没有观察他的项目。 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. 因此,您必须实现ObservableCollection ,它平等地观察他的项目。 This code used in my project found on SO but I can't figure out the post original. 我的项目中使用的这段代码可以在SO上找到,但是我无法弄清楚帖子的原件。 When we add the new item to the collection, it adds an INotifyPropertyChanged event for it. 当我们将新项目添加到集合时,它将为其添加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));
        }
    }
}

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 最后但并非最不重要的一点是,您的模型必须实现INotifyPropertyChanged

public class CfgData: INotifyPropertyChanged
{

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ObservableCollection:在更新值时引发事件 - ObservableCollection: raising event when updating values 在ObservableCollection中更改模型属性时更新UI? - Updating UI when a model property changes in an ObservableCollection? 嵌套属性更改时,抛出ObservableCollection的CollectionChanged - Throw CollectionChanged of ObservableCollection when nested Property changes 当ObservableCollection中的元素的属性发生变化时更新ListBox项目 - Update ListBox Items when there are changes in property of element in ObservableCollection 刷新ObservableCollection <T> 当T中的属性更改时-WPF MVVM - Refresh ObservableCollection<T> when a property in T changes - WPF MVVM 为什么对单个绑定项进行更改不会刷新ObservableCollection中的该项? - Why does raising changes on an individual bound item not refresh that item in an ObservableCollection? 当 Item 改变时通知 ObservableCollection - Notify ObservableCollection when Item changes 引发自定义事件时出错 - Error when raising custom event 当发生两个并发更改时,为什么RowVersion属性没有引发乐观并发异常? - Why RowVersion property is not raising optimistic concurrency exception when two concurrent changes occur? 属性或变量更改值时触发事件 - Fire event when a property or variable changes value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM