【发布时间】:2018-07-30 10:03:49
【问题描述】:
我想在 DataGrid 中的属性发生更改时引发事件以检查它是否有效,将其保存回我的源文件等。
背景信息: 我有一个绑定到可观察集合的 DataGrid。 此时我已经成功地将我的 Observable 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;
但是,当我更改数据网格时,那些从未调用过函数。
问题 如何创建在属性更改时调用的事件处理程序?我必须保存整个数据集还是只保存更改的数据行/属性?
【问题讨论】:
标签: c# wpf events datagrid prism