RoutedCommandsが実行され、プレビューするイベント
-
10-10-2019 - |
質問
私の問題は、複数の場所でコマンドを処理したいということです。たとえば、ボタンが何らかのコマンドにバインドされているカスタムUserControlがあります。そのコントロールにコマンドバインディングがありますが、このコントロールを使用するウィンドウにコマンドバインディングもあります。
私の目的は、ウィンドウ内のコマンドの処理を中断しないで、コントロール内で何らかのアクションを実行することです。
実行され、プレビューするイベントを試してみましたが、運はありませんでした。次に、1つのウィンドウ(以下に掲載されているコード)で問題をシミュレートしました。
<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:
コマンドバインディングについては、非常に興味深く、知っておくべき重要です。
CommandManagerは、ルーティングされたイベントを使用して、コマンドの実行が呼び出された別のコマンドバインドオブジェクトに通知します(デフォルトのジェスチャー、入力バインディング、明示的に)。
今まで、これはかなり簡単です。ただし、さらに重要なのは、コマンドバインディングが、ハンドラーが実行されるとすぐに処理されたCommandManagerからのルーティングイベントをマークすることです(プレビューエクスカチまたは実行)。
最後に、ハンドラーがexecuedRoutedEventHandlerと呼ばれる代表者に一致するプロトタイプを持っていたとしても、コマンドバインディングから実行されたイベントはルーティングベントではなく、通常のCLRイベントです。 E.Handled Flagをfalseに設定または残しても、何も変わりません。
したがって、実行またはプレビューするハンドラーが呼び出されるとすぐに、RoutedCommandはルーティングを停止します。