2011-01-12 20 views
6

我的問題是我想處理多個地方的命令。例如,我有我的自定義UserControl其中一個Button綁定到某些命令。我在該控件中綁定了一個命令,但我也在使用此控件的Window中綁定了一個命令。RoutedCommands執行和預覽執行的事件

我的目標是在控制器內執行一些操作,而不會中斷窗口中命令的處理。

我試着用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,但這沒有什麼區別。誰能解釋這種行爲?

回答

9

我不知道爲什麼發生這種情況(以及它是如何不是bug),但這裏是寫於WPF wiki

有一個關於 特殊性的CommandBinding這是非常有趣的 和重要的是要知道。

命令管理使用路由事件 通知不同的CommandBinding 對象的命令執行是 調用(通過默認手勢, 輸入綁定,明確地,等)。

截至目前,這是相當直接的 。然而,更重要的是 重要的是,會的CommandBinding標誌着 從 命令管理路由事件作爲一個 處理程序被執行,儘快處理(無論是 PreviewExecuted或執行)。

最後,即使您的處理程序有一個從 的CommandBinding匹配一個名爲ExecutedRoutedEventHandler代表 的 執行的事件 原型是不是RoutedEvent,但一個正常的CLR 事件。設置或將 e.Handled標誌設置爲false將不會改變 。

因此,一旦已執行或 PreviewExecuted處理程序被調用, 的的RoutedCommand將停止其 路由。

+1

有什麼辦法可以強制`RoutedCommand`繼續路由嗎? – 2011-07-12 19:58:09