[英]Retrieve databound object for selected row in datagrid
当前,我正在以这种方式从datagrid(WPF)中检索所选行的实际数据绑定对象:
private void PointListDataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
PointItem pointItem = (sender as DataGrid).CurrentItem as PointItem;
}
它有效,但这很不雅致,需要我两次投射。
Treeview有一个SelectedItemChanged事件,该事件使我可以从事件参数中检索数据绑定对象,但找不到用于DataGrid的相同方法的方法。
如何检索所选行的数据绑定对象?
您可以只将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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.