我有一个包含复选框的数据网格。我想在单击行时更改绑定的Selected属性的值:
注意:我不想使用SelectedItemChanged事件,因为当网格中只有一行时,这不能正常工作。
答案 0 :(得分:7)
通常我会找到自己的解决方案:
将MouseLeftButtonUp事件添加到datagrid:
<data:DataGrid x:Name="dgTaskLinks"
ItemsSource="{Binding TaskLinks}"
SelectedItem="{Binding SelectedTaskLink, Mode=TwoWay}"
MouseLeftButtonUp="dgTaskLinks_MouseLeftButtonUp"
>...
并walk the visual tree获取数据网格行:
private void dgTaskLinks_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
///get the clicked row
DataGridRow row = MyDependencyObjectHelper.FindParentOfType<DataGridRow>(e.OriginalSource as DependencyObject);
///get the data object of the row
if (row != null && row.DataContext is TaskLink)
{
///toggle the IsSelected value
(row.DataContext as TaskLink).IsSelected = !(row.DataContext as TaskLink).IsSelected;
}
}
找到后,切换绑定的IsSelected属性是一种简单的方法: - )
希望这有助于其他人。
答案 1 :(得分:0)
这是一个更简单的解决方案
XAML
<data:DataGrid
x:Name="dgMyDataGrid"
ItemsSource="{Binding MyList}"
SelectedItem="{Binding MyList, Mode=TwoWay}"
MouseLeftButtonUp="dgMyDataGrid_MouseLeftButtonUp">...
CS
private void dgMyDataGrid_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
DataGrid dg = (sender as DataGrid);
var allObjects = dg.DataContext as List<MyCustomObject>;
foreach(var o in allObjects)
{
o.Selected = false;
}
MyCustomObject SelectedObject = (MyCustomObject)dg.SelectedItem;
SelectedObject.Selected = true;
}
注意:这个以及另一个例子假设您的类绑定到控件实现INotifyPropertyChanged