Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silverlight Datagrid Row Click

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 http://lh4.ggpht.com/_L9TmtwXFtew/Sw6YtzRWGEI/AAAAAAAAGlQ/pntIr2GU6Mo/image_thumb%5B3%5D.png

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.

like image 292
Mark Cooper Avatar asked Nov 26 '09 15:11

Mark Cooper


1 Answers

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.

like image 101
Mark Cooper Avatar answered Sep 23 '22 13:09

Mark Cooper