c# - 数据网格单元格单击事件

标签 c# .net wpf xaml datagrid

<UserControl x:Class="DDCUI.CommDiagnosisWPFCtrl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" Height="800" Width="300">
    <StackPanel>
        <DataGrid MinHeight="300" MaxHeight="600" AutoGenerateColumns="False" Name="DGComm" CanUserResizeColumns="True" IsReadOnly="True" ItemsSource="{Binding Source=dataGridRows}">
            <DataGrid.Columns>
                <DataGridTextColumn Header="No." Binding="{Binding Number}" Width="0.1*"/>
                <DataGridTextColumn Header="Time" Binding="{Binding Time}" Width="0.1*" />
                <DataGridTextColumn Header="Protocol" Binding="{Binding Protocol}" Width="0.15*" />
                <DataGridTextColumn Header="Source" Binding="{Binding Source}" Width="0.15*" />
                <DataGridTextColumn Header="Destination" Binding="{Binding Destination}" Width="0.15*" />
                <DataGridTextColumn Header="Data" Binding="{Binding Data}" Width="0.5*" />
            </DataGrid.Columns>
        </DataGrid>
        <RichTextBox Height="150" Name="RtbHexCode"/>
        <TreeView  Height="200" Name="TreeViewDecode"/>

    </StackPanel>
</UserControl>
private void DGComm_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
    //e.AddedCells[0].Column
    IList<DataGridCellInfo> cells = e.AddedCells;
    foreach (DataGridCellInfo di in cells)
    {
        DataRowView dvr = (DataRowView)di.Item;
        MessageBox.Show(di.ToString());
    }
}

我希望能够操作选定的单元格。我正在尝试打印单击的单元格的名称,但它在 DataRowView dvr = (DataRowView)di.Item; 上抛出无效的转换异常。指出我无法将 DataSource 转换为 RowView。

如何解决这个问题?

编辑:Itemsources 由提供

public ObservableCollection<object> dataGridRows = new ObservableCollection<object>();

private void InitProtocolParsers()
        {
            DGComm.ItemsSource = dataGridRows;

最佳答案

您通过 di.Item 访问的对象不是 DataRowView 类型而是您绑定(bind)到的实际业务对象。 所以无论你在 ObservableCollection<object> 中放入什么,可以通过di.Item"访问.

尝试一下

MessageBox.Show(di.Item.ToString()) 

我希望这会变得更加清晰。

关于c# - 数据网格单元格单击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11623434/

相关文章:

c# - Java/C# 消息传递的 REST 架构的性能

c# - 如何删除 int (C#) 中的最后一位数字?

.net - 互联网上基于客户端/服务器消息的架构

c# - 溢出检查不起作用

android - 如何创建多平台本地化解决方案?

wpf - Silverlight 和 XBAP 有什么区别?

c# - 检索数据库兼容性级别 - 相同服务器/数据库、不同用户的不同结果

c# - 事务超时

wpf - DataGrid中粗体更改的单元格

c# - 绑定(bind)到 WPF 组合框中的选定内容