我的问题是我想在多个地方处理一个命令。例如,我有我的自定义 UserControl,其中 Button 绑定到某个命令。我在该控件中有一个命令绑定,但在使用此控件的窗口中也有一个命令绑定。
我的目标是在控件内部执行一些操作,同时不中断窗口中命令的处理。
我尝试尝试 Executed 和 PreviewExecuted 事件,但没有运气。然后我在一个窗口中模拟了这个问题(代码贴在下面)。
<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,但它没有任何区别。谁能解释这种行为?