2010-08-02 27 views
0

我正在創建一個將文本框控件作爲目標的命令。WPF命令 - 更改目標控件的屬性

代碼來創建命令:

public class Commands 
{ 
    public static RoutedCommand Appender; 

    static Commands() 
    { 
     Appender = new RoutedCommand(); 
    } 

    public static void AppenderExecuted(object target, ExecutedRoutedEventArgs e) 
    { 
     System.Windows.Controls.TextBox targetTbox = target as System.Windows.Controls.TextBox; 
     if (targetTbox != null) 
     { 
      targetTbox.Text += "AppendedText"; 
     } 
    } 
} 

XAML:

<StackPanel Name="span" FocusManager.IsFocusScope="True"> 
    <Menu IsMainMenu="True"> 
     <MenuItem Header="Tools"> 
      <MenuItem Header="_Append" Name="menuAppend" /> 
     </MenuItem> 
    </Menu> 
    <TextBox Height="100" Name="txtEdit"></TextBox> 
</StackPanel>  

CS:窗口構造函數:

 //create bindings 
     CommandBinding bindingTM = new CommandBinding(Commands.Appender, Commands.AppenderExecuted); 

     //[THIS DOESN'T WORK] 
     this.CommandBindings.Add(bindingTM); 

     //[THIS WORKS] 
     txtEdit.CommandBindings.Add(bindingTM); 

     //associate command 
     menuAppend.Command = Commands.Appender; 

我希望能夠在使用追加程序命令Window上的任何TextBox,而不需要將命令綁定添加到每個TextBox。

- >爲什麼不添加命令綁定到Window不起作用?
- >任何解決方案?

回答

1

嘗試:

public static void AppenderExecuted(object target, ExecutedRoutedEventArgs e) { 
    System.Windows.Controls.TextBox targetTbox = e.OriginalSource as System.Windows.Controls.TextBox; 
    if (targetTbox != null) { 
      targetTbox.Text += "AppendedText"; 
    } 
}