在datagrid的OntargetUpdated事件中获取单元格的单元ID或内容



我有一个绑定到数据的数据,我已经实现了OnTargetUpdated。读/写两个单元格variables和复选框isLive。如果我更改变量或复选框,我会反弹到OnTargetUpdated

<DataGrid AutoGenerateColumns="False" Grid.Row="3" Height="126" HorizontalAlignment="Left" Margin="-1,0,0,0" Name="dg_queue" VerticalAlignment="Top" Width="1446" Grid.ColumnSpan="6" ItemsSource="{Binding QueueItems}" TargetUpdated="OnTargetUpdated">
    <DataGrid.Columns>
        <DataGridTextColumn Header="ID" Width="30" Binding="{Binding Id, StringFormat={}{0:N0}}" IsReadOnly="True"/>
        <DataGridTextColumn Header="Submit Time" Width="80" Binding="{Binding Submit_Time, Converter={StaticResource TimeConverter}}" />
        <DataGridTextColumn Header="Strategy" Width="80" Binding="{Binding Strategy}" IsReadOnly="True"/>
        <DataGridTextColumn Header="Variables" Width="200" Binding="{Binding Variables, NotifyOnTargetUpdated=True}" IsReadOnly="False"/>
        <DataGridCheckBoxColumn Header="Is Live" Width="SizeToHeader" Binding="{Binding Is_Live, NotifyOnTargetUpdated=True}" IsReadOnly="False"/>                
        <DataGridTextColumn Header="Status" Width="60" Binding="{Binding Status}" IsReadOnly="True"/>
    </DataGrid.Columns>
</DataGrid>

如果我将变量或复选框我弹跳到OnTargetUpdated,则如预期:

private void OnTargetUpdated(Object sender, DataTransferEventArgs args)
{
    // Something Changed in the Grid.  
    // if is Is_Live or Variables let's do something useful            
}

我的问题是如何从发送者或我的args告诉我更改的内容(即复选框或文本框(变量)或我不在乎的东西)以触发事件?

我认为您的任务更合适的CellEditEnding事件:

发生在牢房编辑或取消之前。

使用的示例:

XAML

<DataGrid Name="MyDataGrid" 
          AutoGenerateColumns="False" 
          CellEditEnding="MyDataGrid_CellEditEnding" ... />           

Code-behind

private void MyDataGrid_CellEditEnding(object sender, System.Windows.Controls.DataGridCellEditEndingEventArgs e)
{
    DataGrid dataGrid = sender as DataGrid;
    if (e.EditAction == DataGridEditAction.Commit)
    {
        if (e.Column.Header.Equals("Variables"))
        {
            TextBox textBox = e.EditingElement as TextBox;
            MessageBox.Show(textBox.Text);
        }
        else if (e.Column.Header.Equals("IsLive"))
        {
            CheckBox checkBox = e.EditingElement as CheckBox;
            MessageBox.Show(checkBox.IsChecked.ToString());
        }
    }
}

尽管它有效,但我认为它看起来很困难,而是一种风格的Winforms,而不是WPF。在这种情况下,您可以跟踪事件INotifyPropertyChanged接口,并执行类似的操作:

从答案中获取:WPF datagrid列:如何管理值的事件更改

在视图模型构造函数中:

SelectedItem.PropertyChanged += SelectedItem_PropertyChanged;

在视图模型中:

private void SelectedItem_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    // this will be called when any property value
    // of the SelectedItem object changes
    if (e.PropertyName == "YourPropertyName") DoSomethingHere();
    else if (e.PropertyName == "OtherPropertyName") DoSomethingElse();
}

在UI中:

<DataGrid ItemsSource="{Binding Items}"
          SelectedItem="{Binding SelectedItem}" ... />

另外,我建议查看引用答案:

wpf datagrid列:如何管理价值更改的事件

最新更新