How do I use the MouseWheel event to scroll through the TabItems of nested TabControls?
I have a TabControl that can contain a TabControl in each TabItem. There is the xaml-code:
<TabControl Height="300" Width="500" MouseWheel="TabControl_MouseWheel">
<TabItem Header="1" Width="50">
<TabControl MouseWheel="TabControl_MouseWheel">
<TabItem Header="1" Width="50"></TabItem>
<TabItem Header="2" Width="50"></TabItem>
<TabItem Header="3" Width="50"></TabItem>
<TabItem Header="4" Width="50"></TabItem>
<TabItem Header="5" Width="50"></TabItem>
<TabItem Header="6" Width="50"></TabItem>
<TabItem Header="7" Width="50"></TabItem>
<TabItem Header="8" Width="50"></TabItem>
<TabItem Header="9" Width="50"></TabItem>
</TabControl>
</TabItem>
<TabItem Header="2" Width="50">
<TabControl MouseWheel="TabControl_MouseWheel">
<TabItem Header="1" Width="50"></TabItem>
<TabItem Header="2" Width="50"></TabItem>
<TabItem Header="3" Width="50"></TabItem>
<TabItem Header="4" Width="50"></TabItem>
<TabItem Header="5" Width="50"></TabItem>
<TabItem Header="6" Width="50"></TabItem>
<TabItem Header="7" Width="50"></TabItem>
<TabItem Header="8" Width="50"></TabItem>
<TabItem Header="9" Width="50"></TabItem>
</TabControl>
</TabItem>
<TabItem Header="3" Width="50"></TabItem>
<TabItem Header="4" Width="50"></TabItem>
<TabItem Header="5" Width="50"></TabItem>
<TabItem Header="开发者_JAVA技巧6" Width="50"></TabItem>
<TabItem Header="7" Width="50"></TabItem>
<TabItem Header="8" Width="50"></TabItem>
<TabItem Header="9" Width="50"></TabItem>
</TabControl>
I want to change the selected item of tabcontrols by mouse wheeling. There is MouseWheel event handler:
private void TabControl_MouseWheel(object sender, MouseWheelEventArgs e)
{
TabControl tabControl = sender as TabControl;
if (tabControl != null)
{
if (e.Delta < 0)
{
if (tabControl.SelectedIndex + 1 < tabControl.Items.Count)
tabControl.SelectedItem = tabControl.Items[tabControl.SelectedIndex + 1];
}
else
{
if (tabControl.SelectedIndex - 1 > -1)
tabControl.SelectedItem = tabControl.Items[tabControl.SelectedIndex - 1];
}
}
}
The problem is that scrolling with the mouse wheeling just changes the selected item in the upper TabControl. I want other TabControls to react to mouse wheeling too.
For example: if the cursor is in one of the upper TabControl items then I want them to react to mouse wheel scrolling, otherwise I want the lower TabControls items to react to the scrolling.
The inner TabControls
do react, but you barely notice as the outer tab switches as well, just add the line e.Handled = true
at the very end of the handler and it should work as expected as the event will no longer bubble through to the outer handler.
(By the way, as the event bubbles you can make this work only adding a handler to the event on the outer TabControl, you then need to change the logic on the handler a bit to get the "closest" TabControl though)
精彩评论