简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM