覆盖ApplicationCommands。可编辑WPF组合框的副本

问题描述 投票:0回答:1

我正在重写ApplicationCommands.Copy,在许多控件上都取得了成功,但无法弄清楚如何使其与WPF中的可编辑ComboBox一起使用。例如,一个TextBox可以像这样正常工作:

 var copyCommandBinding = new CommandBinding(ApplicationCommands.Copy, CopyToClipboardExecuted);
 MyTextBox.CommandBindings.Add(copyCommandBinding); // Works as expected

[当我尝试对可编辑的ComboBox执行相同操作时,即使我为CanExcute返回true,也无法使用:

 var copyCommandBinding = new CommandBinding(ApplicationCommands.Copy, CopyToClipboardExecuted);
 MyComboBox.CommandBindings.Add(copyCommandBinding);  // Nothing happens

我通过添加KeyUp事件处理程序并测试CTRL + C来解决此问题,这似乎不是正确的解决方案:

 public MyWindow()
 {
      MyComboBox.KeyUp += MyComboBox_KeyUp;
 }

 private void MyComboBox_KeyUp(object sender, KeyEventArgs e)
 {
      if (!Keyboard.IsKeyDown(Key.LeftCtrl) && !Keyboard.IsKeyDown(Key.RightCtrl)) return;
      if (e.Key == Key.C) CopyToClipboardExecuted();
 }

我确实知道,在可编辑的ComboBox上添加TextChanged事件处理程序需要花费一些额外的工作来利用TestBoxBase的事件,所以我想知道是否有类似的技巧来获得对相同TextBoxBase的ApplicationCommands.Copy支持。我似乎找不到涵盖此细节的任何文档。

感谢任何猜测,帮助或暗示,谢谢!

c# wpf combobox copy-paste editable
1个回答
0
投票

我的假设是正确的,稍加挖掘便得出了答案。为此,要访问ComboBox的TextBoxBase,必须使用Template.FindName()方法。 documentation显示可以找到“ PART_EditableTextBox”。您也可以使用找到的参考来在TextBoxBase上设置事件处理程序。唯一的问题是您只能在呈现控件后才能这样做:

private void MyWindow_ContentRendered(object sender, EventArgs e)
{
    // Intercept Copy at Window
    CommandBinding copyCommandBinding = new CommandBinding(ApplicationCommands.Copy, CopyToClipboardExecuted);
    CommandBindings.Add(copyCommandBinding);

    // Intercept Copy within TextBox
    MyTextBox.CommandBindings.Add(copyCommandBinding);

    // Intercept Copy within ComboBox
    TextBox comboTextBox = MyTextBox.Template.FindName("PART_EditableTextBox", MyTextBox) as TextBox;
    comboTextBox.CommandBindings.Add(copyCommandBinding);
    comboTextBox.TextChanged += MyComboBox_TextChanged;
}
© www.soinside.com 2019 - 2024. All rights reserved.