wpf 数据网格单元格点击事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11623434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Datagrid Cell Click event
提问by l46kok
<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());
}
}
I want to be able to manipulate the selected cell. I'm trying to print the name of the cell clicked but it is throwing an invalid cast exception on DataRowView dvr = (DataRowView)di.Item; stating that I cannot convert a DataSource into RowView.
我希望能够操作选定的单元格。我正在尝试打印单击的单元格的名称,但它在 DataRowView dvr = (DataRowView)di.Item; 上抛出了一个无效的强制转换异常;声明我无法将 DataSource 转换为 RowView。
How can I fix this issue?
我该如何解决这个问题?
Edit: Itemsources is provided by
编辑:Itemsources 由
public ObservableCollection<object> dataGridRows = new ObservableCollection<object>();
private void InitProtocolParsers()
{
DGComm.ItemsSource = dataGridRows;
回答by Wolfgang Ziegler
The object you are accessing via di.Itemis not of type DataRowViewbut the actual business object you are binding to.
So whatever you put in your ObservableCollection<object>can be accessed via di.Item".
您通过访问的对象di.Item不是类型,DataRowView而是您绑定到的实际业务对象。因此,您放入的任何内容ObservableCollection<object>都可以通过di.Item".
Just try
你试一试
MessageBox.Show(di.Item.ToString())
and this will get clearer, I hope.
我希望这会变得更清楚。

