我有一个DataGrid
绑定到ObservableCollection
DataRowView
。在我开始输入之前调用DataGrid.BeginningEdit
。焦点丢失后调用CellEditEnding
。我需要一个在单元格上键入时触发的事件。我该怎么办?
private static ObservableCollection<DataRowView> _dataGridSrcCollection = new ObservableCollection<DataRowView>();
public static ObservableCollection<DataRowView> DataGridSrcCollection
{
get
{
return _dataGridSrcCollection;
}
set
{
if (value != _dataGridSrcCollection)
{
_dataGridSrcCollection = value;
}
}
}
我以编程方式绑定每一列。
答案 0 :(得分:0)
我怀疑CellValueChanged
有DataGrid
个事件,但假设您的所有数据网格列都是文本列,那么您可以使用TextChanged
事件,如下所示:
的Xaml:
<DataGrid Grid.Row="0"
ItemsSource="{Binding DataGridSrcCollection}"
SelectionUnit="Cell"
SelectionMode="Single" >
<DataGrid.Columns>
<DataGridTextColumn Header="your header" Binding="{Binding Path=YourProperty}" >
<DataGridTextColumn.EditingElementStyle>
<Style TargetType="{x:Type TextBox}">
<EventSetter Event="TextChanged" Handler="CellValueChanged" />
</Style>
</DataGridTextColumn.EditingElementStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
代码背后:
private void CellValueChanged(object sender, TextChangedEventArgs e)
{
// your code
}
答案 1 :(得分:0)
首先,由于您说您以编程方式绑定列,因此需要将Binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
添加到这些绑定中。
然后,您需要订阅集合中每个DataRowView对象的PropertyChanged
事件。执行此操作以避免松散事件处理程序的最佳方法是在ObservableCollection的CollectionChanged
事件中,如下所示:
private static ObservableCollection<DataRowView> _dataGridSrcCollection = new ObservableCollection<DataRowView>();
public static ObservableCollection<DataRowView> DataGridSrcCollection
{
get
{
return _dataGridSrcCollection;
}
set
{
if (value != _dataGridSrcCollection)
{
if (_dataGridScrCollection != null)
{
_dataGridScrCollection.CollectionChanged -= DataGridScrCollection_CollectionChanged;
foreach (var row in _dataGridScrCollection)
row.PropertyChanged -= DataRowView_PropertyChanged;
}
if (value != null)
{
value.CollectionChanged += DataGridScrCollection_CollectionChanged;
foreach (var row in value)
row.PropertyChanged += DataRowView_PropertyChanged;
}
_dataGridSrcCollection = value;
}
}
}
private void DataGridScrCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
foreach (var item in e.OldItems)
((DataRowView)item).PropertyChanged -= DataRowView_PropertyChanged;
if (e.NewItems != null)
foreach (var item in e.NewItems)
((DataRowView)item).PropertyChanged += DataRowView_PropertyChanged;
}
private void DataRowView_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
// This will be called every time a change is made to any cell
}