Search code examples
wpfdatagridsender

How to get the checkbox column sender's datagrid parent


Hi I have a datagrid (xaml code below):

<DataGrid.Columns>
                        <DataGridTextColumn Header="FLEET" IsReadOnly="True" Width="1*" Binding="{Binding FLEET, UpdateSourceTrigger=PropertyChanged}" /> 

                        <DataGridTemplateColumn Header="SELECTED?" Width="1*">
                            <DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <Viewbox Margin="-0.2" Height="18.5">
                                        <CheckBox IsThreeState="True" IsChecked="{Binding Path=isSelected, UpdateSourceTrigger=PropertyChanged}" Click="FSC_CheckBox_Click"/>

                                    </Viewbox>
                                </DataTemplate>
                            </DataGridTemplateColumn.CellTemplate>
                        </DataGridTemplateColumn>
                    </DataGrid.Columns>

The click events:

 private void FSC_CheckBox_Click(object sender, RoutedEventArgs e)
    {
     ......
    }

Is there a way I can get the the parent datagrid object from the click sender? I've tried this link Get containing row from a CheckBox inside of a DataGrid, but it didn't work because of the viewbox and datatemplate(I guess). Any suggestions is appreciated. Thank you.


Solution

  • The click event handler will get the sender, which you can cast to checkbox.
    I reckon the simplest approach is to abuse the Tag property on your checkbox.
    That can be any old object you fancy.
    You can use a relativesource binding for that.
    Something like:

    <CheckBox Tag="{Binding RelativeSource={Relativesource AncestorType=DataGrid}}"
    

    Grab it off there, roughly:

     private void FSC_CheckBox_Click(object sender, RoutedEventArgs e)
     {
           var cb=(CheckBox)sender;
           var parentDataGrid = (DataGrid)cb.Tag;
     }
    

    This is air code, I don't have a datagrid with a checkbox and a click handler to try it out with easily so there may be some typo lurking.