2009-06-12 18 views
3

我可以通過某種方式擴展WPF命令路由,以便首先檢查命令是否可以在焦點字段中調用,如果不是在其他(永不改變)中調用?有沒有鉤?也許你不知道這是否會起作用,但在網上看到類似的東西,並可以節省鏈接?如何重寫WPF路由命令調度機制

摘要例如

因爲如果我會寫一個側板和麪板將有焦點的文本編輯器的例子。如果我按Ctrl + G,將會調用一些命令,因爲面板具有命令綁定和焦點(即正常的WPF行爲)。另外,如果我按Ctrl + H,但此時面板沒有調用命令的命令綁定。在這種情況下,我希望路由引擎切換到文本編輯器並將相同的命令發送到那裏。

真實的例子

我有說粘貼,但重點是側面面板上的菜單項。如果我按菜單命令綁定到面板將被執行。假設沒有合適的命令綁定到面板。在這種情況下,我想粘貼到文本編輯器中。

代碼

此代碼或多或少地代表了這種情況。我想按Ctrl + H和執行CommandBinding_Executed_1

Window1.xaml

<Window x:Class="WpfApplication1.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:WpfApplication1"> 
    <StackPanel>   
     <TextBox x:Name="textBlock1"> 
      <TextBox.CommandBindings> 
       <CommandBinding Command="local:Window1.TestCommand" Executed="CommandBinding_Executed_1" /> 
       <CommandBinding Command="local:Window1.ForwardedTestCommand" Executed="CommandBinding_Executed_1" /> 
      </TextBox.CommandBindings> 
     </TextBox> 
     <TextBox x:Name="textBlock2"> 
      <TextBox.CommandBindings> 
       <CommandBinding Command="local:Window1.TestCommand" Executed="CommandBinding_Executed_2" /> 
      </TextBox.CommandBindings> 
      <TextBox.InputBindings> 
       <KeyBinding Command="local:Window1.TestCommand" Gesture="Ctrl+G" /> 
       <KeyBinding Command="local:Window1.ForwardedTestCommand" Gesture="Ctrl+H" /> 
      </TextBox.InputBindings> 
     </TextBox> 
    </StackPanel> 
</Window> 

Window1.xaml.cs

using System.Windows; 
using System.Windows.Input; 

namespace WpfApplication1 
{ 
    public partial class Window1 : Window 
    { 
     public static RoutedUICommand TestCommand = new RoutedUICommand("TestCommand", "TestCommand", typeof(Window1)); 
     public static RoutedUICommand ForwardedTestCommand = new RoutedUICommand("ForwardedTestCommand", "ForwardedTestCommand", typeof(Window1)); 

     public Window1() 
     { 
      InitializeComponent(); 
     } 

     private void CommandBinding_Executed_1(object sender, ExecutedRoutedEventArgs e) 
     { 
      MessageBox.Show("CommandBinding_Executed_1"); 
     } 

     private void CommandBinding_Executed_2(object sender, ExecutedRoutedEventArgs e) 
     { 
      MessageBox.Show("CommandBinding_Executed_2"); 
     } 
    } 
} 

回答

0

我能解決這個問題是這樣的使用Window.AddHandler方法捕獲所有路由命令事件,然後像這樣從textBlock1重新引發它們。

textBlock1.RaiseEvent(e);

我沒有爲一個代碼還沒有,但這個想法是,如果不處理路由事件冒泡到窗口範圍,我們捕捉所有未處理的事件,並從主窗口區域

重新提出來