我正在创建一个将文本框控件作为目标的命令。
创建命令的代码:
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上使用Appender命令,而无需为每个TextBox添加命令绑定。
- &GT;为什么不将命令绑定添加到Window不起作用?
- &GT;任何解决方案?
答案 0 :(得分: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";
}
}