您可以将 PointItem 类型的属性添加到 DataContext 类(例如,包含 DataGrid 的 Window 或 Page 类)并将 CurrentItem 属性绑定到此属性。然后数据绑定为您处理转换,您不必手动进行:
public PointItem CurrentPointItem
{
get { return (PointItem)GetValue(CurrentPointItemProperty); }
set { SetValue(CurrentPointItemProperty, value); }
}
// Using a DependencyProperty as the backing store for CurrentPointItem. This enables animation, styling, binding, etc...
public static readonly DependencyProperty CurrentPointItemProperty =
DependencyProperty.Register("CurrentPointItem", typeof(PointItem), typeof(MainWindow), new PropertyMetadata(null));
和您的 xaml(当然,您必须将 DataGrid 的 DataContext 属性或其父级之一设置为包含 CurrentPointItem 属性的对象):
<DataGrid CurrentItem={Binding CurrentPointItem} />
比你可以这样写你的事件:
private void PointListDataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
PointItem pointItem = CurrentPointItem;
if (pointItem == null)
{
//no item selected
}
}