DataGrid inside TabItem event handling
-
02-07-2021 - |
Pregunta
I have a TabControl with two TabItems, inside the one TabItem I have a DataGrid. I'm trying to handle the TabItem click, and it works, but, when I click in one row of the "dataGrid1" the event "TabItem_MouseLeftButtonUp" of TabItem click is fired too. See the code:
<TabControl Height="211" HorizontalAlignment="Left" Margin="33,29,0,0" Name="tabControl1" VerticalAlignment="Top" Width="417" >
<TabItem Header="tabItem1" Name="tabItem1">
<Grid />
</TabItem>
<TabItem MouseLeftButtonUp="TabItem_MouseLeftButtonUp">
<DataGrid AutoGenerateColumns="True" Height="134" Name="dataGrid1" Width="307" />
</TabItem>
</TabControl>
Note: I can't use the personalize <TabItem.Header>
because I'm using MahApps, if I use TabItem.Header the style os TabItem will break.
Solución
The MouseLeftButtonUp
event is bubbling routed event. When you on the DataGrid
s row the event bubbling through its ancestors and calls the corresponding handlers, TabItem_MouseLeftButtonUp for TabItem
in your case.
In your TabItem_MouseLeftButtonUp event you can check who raised the event, which control is the origin. If its not the TabItem
do nothing.
private void TabItem_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if(sender is TabItem)
{
//do the work
}
}
Otros consejos
You will recieve the EventArgs with MouseLeftButtonUp event. Just filter out whatever you need.