我的问题是我想在多个地方处理命令。例如,我有自定义用户控件,其中按钮绑定到某个命令。我在该控件中有一个命令绑定,但在使用该控件的窗口中也有一个命令绑定。
我的目标是在控件内执行某些操作,同时不中断窗口中命令的处理。
我尝试尝试执行和预览执行事件,但没有成功。然后我在一个窗口中模拟了该问题(代码如下)。
<Window x:Class="CommandingEvents.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:CommandingEvents="clr-namespace:CommandingEvents"
Title="Window1" Height="300" Width="300">
<Window.CommandBindings>
<CommandBinding
Command="{x:Static CommandingEvents:Window1.Connect}"
Executed="CommandBindingWindow_Executed"
PreviewExecuted="CommandBindingWindow_PreviewExecuted"/>
</Window.CommandBindings>
<Grid>
<Grid.CommandBindings>
<CommandBinding
Command="{x:Static CommandingEvents:Window1.Connect}"
Executed="CommandBindingGrid_Executed"
PreviewExecuted="CommandBindingGrid_PreviewExecuted" />
</Grid.CommandBindings>
<Button Command="{x:Static CommandingEvents:Window1.Connect}"
CommandTarget="{Binding RelativeSource={RelativeSource Self}}"
Content="Test" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>
namespace CommandingEvents
{
public partial class Window1
{
public static readonly RoutedUICommand Connect = new
RoutedUICommand("Connect", "Connect", typeof(Window1));
public Window1()
{
InitializeComponent();
}
private void CommandBindingWindow_Executed(object sender, ExecutedRoutedEventArgs e)
{
Console.WriteLine("CommandBindingWindow_Executed");
e.Handled = false;
}
private void CommandBindingGrid_Executed(object sender, ExecutedRoutedEventArgs e)
{
Console.WriteLine("CommandBindingGrid_Executed");
e.Handled = false;
}
private void CommandBindingWindow_PreviewExecuted(object sender, ExecutedRoutedEventArgs e)
{
Console.WriteLine("CommandBindingWindow_PreviewExecuted");
e.Handled = false;
}
private void CommandBindingGrid_PreviewExecuted(object sender, ExecutedRoutedEventArgs e)
{
Console.WriteLine("CommandBindingGrid_PreviewExecuted");
e.Handled = false;
}
}
}
当我点击按钮时,仅打印出“CommandBindingWindow_PreviewExecuted”。这是为什么?我尝试将 e.Handled 设置为 false,但没有什么区别。谁能解释这种行为?
我不知道为什么会发生这种情况(以及它如何不是一个错误),但这是在WPF wiki:
有一个特殊性是关于
CommandBinding 这是非常
有趣且重要的是要知道。
CommandManager 使用路由事件
通知不同的CommandBinding
命令执行的对象
调用(通过默认手势,
输入绑定、显式等)。
到目前为止,这还算
直截了当。然而,更重要的是
重要的是 CommandBinding 将
标记路由事件
CommandManager 一旦处理
处理程序被执行(或者
预览已执行或已执行)。
最后,即使你的处理者有一个
与委托匹配的原型
称为 ExecutedRoatedEventHandler,
从 CommandBinding 执行的事件
不是 RoutedEvent 而是普通的 CLR
事件。设置或保留
e.Handled flag为false将会改变
没有什么。
因此,一旦执行或
PreviewExecuted 处理程序被调用,
RoutedCommand 将停止其
路由。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)