簡體   English   中英

ObservableCollection中的Property更改時引發事件

[英]Raising event when Property in ObservableCollection changes

我想在更改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;

但是,當我更改數據網格時,那些從未調用過的函數。

問題我如何創建在屬性更改時被調用的事件處理程序? 我必須保存整個數據集還是可以只保存更改后的數據行/屬性?

因為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
{

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM