Maciej Wozniak
Maciej Wozniak

Reputation: 1174

How to access DataGridCell from its child control

I have a DataGrid with template column, containing a checkbox:

<DataGridTemplateColumn Header="Foreign key">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <CheckBox HorizontalAlignment="Center" 
                VerticalAlignment="Center" 
                IsChecked="{Binding ForeignKey,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                PreviewMouseDown="CheckBox_PreviewMouseDown" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

How can I access a DataGridCell containing this checkbox from inside the handler (CheckBox_PreviewMouseDown), having only CheckBox as sender:

private void CheckBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    CheckBox checkBox = sender as CheckBox;
    ???
}

Upvotes: 0

Views: 399

Answers (1)

Claus J&#248;rgensen
Claus J&#248;rgensen

Reputation: 26347

If you need to access the UI control, iterate through the visual tree using a helper. Or, if you just need the databinding, use the Tag property of the CheckBox.

<CheckBox HorizontalAlignment="Center"
          VerticalAlignment="Center"
          IsChecked="{Binding ForeignKey,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
          PreviewMouseDown="CheckBox_PreviewMouseDown"
          Tag="{Binding}" />

Then you can access it in your code, and typecast it to the type of the bound item(s).

Upvotes: 1

Related Questions