I am reading about Routed Event which is very cool concept by the way, I understand how event Bubbling work from child element toward root element but I am not sure about how event tunneling works. I have created small example where I put one button in grid and attached previewKeyup event to all but after pressing key event get handled at root level and not tunneled down to child.

<Window x:Class="ExplorerContentControl.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Content Control" Height="400" Width="400" FontFamily="Calibri" FontSize="13" FontWeight="Bold" Button.Click ="Window_Click" PreviewKeyUp="Window_PreviewKeyUp" >
    <Grid Button.Click ="Grid_Click" PreviewKeyUp="Grid_PreviewKeyUp">
        <Button Name="btnClickedMe" Click="btnClickedMe_Click" Margin="3" HorizontalAlignment="Left" Height="25" Width="80" Content="Click Me" PreviewKeyUp="btnClickedMe_PreviewKeyUp" />
    </Grid>
</Window>

While in Code behind

private void btnClickedMe_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("From Btn Clicked");
}

private void Grid_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("at Grid Location...");
}

private void Window_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("at Windows Location ...");
}

private void Window_PreviewKeyUp(object sender, KeyEventArgs e)
{
    MessageBox.Show("PreviewKeyUp From Windows...");
}

private void Grid_PreviewKeyUp(object sender, KeyEventArgs e)
{
    MessageBox.Show("PreviewKeyUp From Grid...");
}

private void btnClickedMe_PreviewKeyUp(object sender, KeyEventArgs e)
{
    MessageBox.Show("PreviewKeyUp From Button...");
}

While in Event bubbling Proper message box appears from buttonClick to WindowClick but not same scenario in PreviewKeyup. Can some one please explain to me how event tunneling work in my example ?

有帮助吗?

解决方案

It is a tricky way you want to try the tunneling. I think you press the up button if you are in the window and than you get the message only from the window. It is so, because you pressed the up button on the window (the window is the activ control) and the event comes from the route of the window and stops at the window because it was the leaf-element, who triggered the event. Try to click first the "Click me" button and than you got the focus on the button and press the up key. It will tunnel from window through the grid to the button and you will get all the messages you wanted.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top