Reputation: 6884
I have a datagrid with a column containing a checkbox. I want to change the value of the bound Selected property when the row is clicked:
NOTE: I don't want to use the SelectedItemChanged event because this doesn't work properly when there is only one row in the grid.
Upvotes: 7
Views: 18410
Reputation: 7343
Here is an even simpler solution
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;
}
Note: this as well as the other example assumes your class that you are binding to the control implements INotifyPropertyChanged
Upvotes: 0
Reputation: 6884
As is often the way i have found my own solution for this:
Add a MouseLeftButtonUp event to the datagrid:
<data:DataGrid x:Name="dgTaskLinks"
ItemsSource="{Binding TaskLinks}"
SelectedItem="{Binding SelectedTaskLink, Mode=TwoWay}"
MouseLeftButtonUp="dgTaskLinks_MouseLeftButtonUp"
>...
And walk the visual tree to get the data grid row:
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;
}
}
Once found, it is a simple approach to toggle the bound IsSelected property :-)
Hope this helps someone else.
Upvotes: 7