【发布时间】:2014-12-05 18:40:18
【问题描述】:
我在这里的第一篇文章!编码新手!...
我在页面的框架中有一个 WPF 数据网格。我想单击(最好单击)一行并使用存储在其中一列中的 ID 值导航到(打开)一个新页面。
使用 MouseDoubleClick 有时我可以双击行来打开一个页面。但有时它会抛出: “在 program.exe 中发生了“System.NullReferenceException”类型的未处理异常 附加信息:对象引用未设置为对象的实例。”
在线(完整方法见下方代码):
string ID = ((DataRowView)PersonDataGrid.SelectedItem).Row["PersonID"].ToString();
XAML:
<DataGrid x:Name="PersonDataGrid" AutoGenerateColumns="False"
SelectionMode="Single" SelectionUnit ="FullRow"
MouseDoubleClick="PersonDataGrid_CellClicked" >
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=PersonID}"
ClipboardContentBinding="{x:Null}" Header="ID" />
</DataGrid.Columns>
<DataGrid.CellStyle>
<Style TargetType="DataGridCell" BasedOn="{StaticResource myDataGridCellStyle}">
<EventSetter Event="DataGridCell.MouseLeftButtonDown" Handler="PersonDataGrid_CellClicked"/>
</Style>
</DataGrid.CellStyle>
</DataGrid>
代码背后:
private void PersonDataGrid_CellClicked(object sender, MouseButtonEventArgs e)
{
string ID = ((DataRowView)PersonDataGrid.SelectedItem).Row["PersonID"].ToString();
SelectedPersonID = Int32.Parse(ID);
this.NavigationService.Navigate(new PersonProfile());
}
有没有更好的方法来打开 PersonProfile 页面?有没有一种简单的方法可以通过单击一行来打开页面?
谢谢。
【问题讨论】:
-
我删除了 XAML 中的 MouseDoubleClick="PersonDataGrid_CellClicked" 并将其替换为 DataGridCell.Selected="PersonDataGrid_CellClicked" 我现在可以单击打开页面。但是,发送者对象是 DataGridItems.Count,现在程序在 this.NavigationService.Navigate(new PersonProfile()); 上抛出错误
-
使用 Joseph 的示例来实现此功能。感谢两位海报。
标签: c# wpf xaml datagrid click