从父控件添加到命令操作

时间:2013-05-16 21:46:32

标签: c# wpf xaml .net-4.0 command

我有一个自定义控件,它是一个带有嵌入式按钮的文本框,用于清除文本框。该按钮连接到ApplicationCommands.Delete命令,目标作为文本框。这完全符合预期。

我的问题是我有另一个使用此自定义文本框的控件,需要知道执行ApplicationCommands.Delete的时间,以便它可以在默认操作之上运行自己的操作。我试图添加到CommandBindings,但这不起作用。有没有办法在父级UIElement接收命令通知?

TextBox自定义控件XAML

<UserControl.CommandBindings>
    <CommandBinding Command="ApplicationCommands.Delete" Executed="ClearTextBoxExecuted" />
</UserControl.CommandBindings>
...
<Button Command="ApplicationCommands.Delete" CommandTarget="{Binding ElementName=FilteredTextBox}"

代码背后:

private void ClearTextBoxExecuted(object sender, ExecutedRoutedEventArgs e)
{
  if (!(e.OriginalSource is TextBox)) return;
  var textBox = e.OriginalSource as TextBox;
  textBox.Clear();
  if (TextCleared != null)
    TextCleared(sender, null);
}

Xaml由于程序集资源Uri约束而包装文本框

<UserControl x:Class="CopyOfEnhancedTextboxForLocalInheritance" Name="MainWrapper">
<textBoxes:EnhancedTextBox x:Name="EnhancedTextBox"...

HotKeySelectorTextBox:

public class HotKeySelectorBox : CustomTextBox
{
  void SetupCommands()
  {
    var deleteCommand = new CommandBinding(ApplicationCommands.Delete,
                                         (sender, args) => 
                                           DeleteSelection());
    deleteCommand.CanExecute +=
    (sender, args) =>
      {
        args.Handled = true;
        args.CanExecute = !(Text == String.Empty || Text == "none");
      };
    EnhancedTextBox.CommandBindings.Add(deleteCommand);
    CommandBindings.Add(deleteCommand);
  }
}

0 个答案:

没有答案