WPF DataGrid单元格值已更改事件

时间:2015-12-22 19:49:51

标签: c# wpf datagrid

我的设置如下:

// myDG is a DataGrid whose columns are DataGridTextColumn
ObservableCollection<MyItem> myOC;
// myOC is populated with some new MyItem
myDG.ItemsSource = myOC;

其中MyItem实现INotifyPropertyChanged。当用户将值输入单元格时,正确捕获的方法是什么?

我已尝试在PropertyChanged上捕获MyItem,但我也会在后台定期更新值(我们的想法是,当用户手动编辑该值时,会触发一个标记告诉定期计算以避免覆盖手动输入的数据)。因此PropertyChanged捕获所有内容,包括我不想要的定期更新。我想有可能做到这一点(通过在我进行定期计算时设置一个标志,然后在PropertyChanged事件处理程序上检查是否缺少标志 - 但我想知道是否有更简单的解决方案。)

我已尝试捕获myDG.CurrentCellChanged,但每次用户更改单元格选择时都会触发,而不是在编辑单元格内容时触发。

编辑:这是XAML:

<DataGrid x:Name="myDG" ItemsSource="{Binding}" AutoGenerateColumns="False" Margin="10,10,182,0" VerticalAlignment="Top" Height="329" ClipboardCopyMode="IncludeHeader">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Col1" Binding="{Binding Prop1}" IsReadOnly="True"/>
        <DataGridTextColumn Header="Col2" Binding="{Binding Prop2}" IsReadOnly="False"/>
    </DataGrid.Columns>
</DataGrid>

以下是MyItem实施(使用Fody/PropertyChanged):

[ImplementPropertyChanged]
class MyItem : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public string Prop1 { get; set; }
    public string Prop2 { get; set; }

    public MyItem()
    {
        Prop1 = Prop2 = "";
    }
}

2 个答案:

答案 0 :(得分:26)

解决方案是捕获CellEditEnding事件。

// In initialization
myDG.CellEditEnding += myDG_CellEditEnding;

void myDG_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
    if (e.EditAction == DataGridEditAction.Commit)
    {
        var column = e.Column as DataGridBoundColumn;
        if (column != null)
        {
            var bindingPath = (column.Binding as Binding).Path.Path;
            if (bindingPath == "Col2")
            {
                int rowIndex = e.Row.GetIndex();
                var el = e.EditingElement as TextBox;
                // rowIndex has the row index
                // bindingPath has the column's binding
                // el.Text has the new, user-entered value
            }
        }
    }
}

答案 1 :(得分:0)

您可以通过使用 CellEditEnding 事件来实现此目的,另一件事是DataGridTextColumn中必须添加以下某些属性:-

<DataGrid x:Name="myDG" CellEditEnding="myDG_CellEditEnding"  ItemsSource="{Binding}" AutoGenerateColumns="False" Margin="10,10,182,0" VerticalAlignment="Top" Height="329" ClipboardCopyMode="IncludeHeader">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Col1" Binding="{Binding Prop1}" 
 IsReadOnly="True"/>
 <DataGridTextColumn x:Name="dataGridTextColumn"Header="Col2" Binding="{Binding Prop2,  UpdateSourceTrigger=LostFocus, Mode=TwoWay}" Width="*" />
    </DataGrid.Columns>
</DataGrid>

IN C#

 private void myDG_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e) {
            string prop1 = (e.Row.Item as DataRowView).Row[1].ToString();
        }