views:

2214

answers:

2

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:

alt text

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.

+3  A: 

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 :-)

HTH someone else. Mark

Mark Cooper
I like your solution. It makes a little more sense than mine. Although, I'm wondering where you got this 'MyDependencyObjectHelper' class from. I assume its your custom code. Care to share it?
Luke Baulch
It's linked in the the answer under "Walk the visual tree". GLad this helped, Mark
Mark Cooper
+1 Great solution! I spent 3 hours trying to hack a grid to "auto select" a check box and didn't come up with anything nearly as elegant.
dfaivre
+1  A: 

Wouls you please post the code of your FindParentOfType in your MyDependencyObjectHelper?

Jianchi
It can be seen here: http://thoughtjelly.blogspot.com/2009/09/walking-xaml-visualtree-to-find-parent.html. I did link to it in the original question too ;)
Mark Cooper
If you find this useful please upvote me :-D
Mark Cooper