Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top