为什么我的自定义RoutedCommand没有冒泡所有视觉父母?

时间:2017-11-16 22:56:57

标签: wpf routed-commands

一个人为的例子: 窗口 -Grid --StackPanel ---滑块 ---滑块

两个滑块都使用Interaction.Triggers发送在codebehind中定义的自定义命令。每个可视父级定义一个CommandBinding来绑定此Test命令并在后面的代码中调用Executed处理程序。仅命中最近祖先的处理程序:例如如果所有三个绑定都在xaml中,那么只会命中StackPanel_CommandBinding_Executed断点。如果我为StackPanel注释掉CommandBinding,那么下一个父级更高的处理程序将被命中(StackPanel_CommandBinding_Executed)。

虽然这个例子使用了Interaction,但我确实尝试使用更简单的Button Command。结果相同。

我认为我在这里有错误的期望。我曾经以为这个冒泡的命令会检查来自聚焦Slider的处理程序,直到可视树。在每个级别上,如果一个Executed处理程序绑定了该命令,它将被调用。我预计每个处理程序将依次被调用:StackPanel,Grid,Window。我读过Bubbling并没有因为在给定级别找到处理程序而停止,但这不是我的经验。

// in RoutedCommandStackOverflow ns
public class CustomCommands
{
public static readonly RoutedUICommand Test 
= new RoutedUICommand("Test","Test",typeof(CustomCommands));
}

//the Executed handlers are like:
private void StackPanel_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        Debug.Assert(e.Handled == false);            
        Debug.WriteLine("StackPanel_CommandBinding_Executed");
    }


<Window x:Class="RoutedCommandStackOverflow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:iAct="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:RoutedCommandStackOverflow"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">

<Window.CommandBindings>
    <CommandBinding Command="{x:Static local:CustomCommands.Test}" Executed="Window_CommandBinding_Executed"/>
</Window.CommandBindings>

<Grid>
    <Grid.CommandBindings>
        <CommandBinding Command="{x:Static local:CustomCommands.Test}" Executed="Grid_CommandBinding_Executed"/>
    </Grid.CommandBindings>

    <StackPanel>

        <StackPanel.CommandBindings>
            <CommandBinding Command="{x:Static local:CustomCommands.Test}" Executed="StackPanel_CommandBinding_Executed"/>
        </StackPanel.CommandBindings>

        <Slider Name="gridSlider1" Margin="10">
            <iAct:Interaction.Triggers>
                <iAct:EventTrigger EventName="GotFocus">
                    <iAct:InvokeCommandAction Command="{x:Static local:CustomCommands.Test}"/>
                </iAct:EventTrigger>
            </iAct:Interaction.Triggers>
        </Slider>

        <Slider Name="gridSlider2" Margin="10">
            <iAct:Interaction.Triggers>
                <iAct:EventTrigger EventName="GotFocus">
                    <iAct:InvokeCommandAction Command="{x:Static local:CustomCommands.Test}"/>
                </iAct:EventTrigger>
            </iAct:Interaction.Triggers>
        </Slider>

    </StackPanel>
</Grid>

0 个答案:

没有答案