【问题标题】:How to create a event handler for event handler?如何为事件处理程序创建事件处理程序?
【发布时间】:2013-12-24 20:13:17
【问题描述】:

我正在创建一个 Custom Control 继承 TextBox,但是,因为 PreviewTextInputTextInput 默认情况下在 TextBox 中不处理,我想实现一个 PreviewTextInputLinkedTextInputLinked 用于我的控制,只是开发人员可以使用+=-=添加或删除这两个事件

我创建了一个名为 PreviewTextInputLinked TextInputLinked

TextCompositionEventHandler
public event TextCompositionEventHandler /*PreviewTextInputLinked*/ TextInputLinked = delegate { };
public MyTextBox()
{
   this.AddHandler(TextBox.PreviewTextInputEvent, /*PreviewTextInputLinked */TextInputLinked, true);
}

在 XAML 程序中

/*<UControls:MyTextBox VerticalAlignment="Top" AcceptLetters="9" Mask=""
                     Width="122" 
                     PreviewTextInputLinked="MyTextBox_PreviewTextInputLinked"/>*/
<UControls:MyTextBox VerticalAlignment="Top" Width="122" 
                     TextInputLinked="MyTextBox_TextInputLinked"/>

后面的代码

private void /*MyTextBox_PreviewTextInputLinked*/ MyTextBox_TextInputLinked(object sender,
                                              TextCompositionEventArgs e)
{
   MessageBox.Show("test");
}

但它什么也没做,也许我做错了,但我不知道我还能做什么

问题出在哪里?

【问题讨论】:

  • 为什么不使用 TextBox TextInputPreviewTextInput
  • 因为它们没有与TextBox“链接”,如果我直接使用this.TextInput += MyEvent;它不起作用,需要使用 AddHandler 才能工作,我想简化一下
  • 我没听懂。如果我使用&lt;UControls:MyTextBox PreivewTextInput="MyTextBox_PreviewTextInput"/&gt;。处理程序被正确调用。
  • 哇!我现在试了一下,你是对的,PreviewTextInput 只需要使用默认事件,但是 TextInput 不能这样使用
  • 那么,TextInput 能做到吗?

标签: c# wpf events controls


【解决方案1】:

PreviewTextInput 可以工作,因为这是 tunnelling event,而 TextInputbubble event。如果在向上路由时处理它,它不会冒泡到可视化树,这就是为什么挂钩到 PreviewTextInput 有效而 TextInput 无效,因为它可能在冒泡途中的某个地方处理。

AddHandler 是一种实现您正在使用的方法。注意它的第三个布尔参数,它对应于handledEventsToo,即你仍然希望调用处理程序,即使它是由某个元素在 Visual Tree 下方处理的。

现在您的代码中的问题是you pass an empty delegate,它将按照您的意愿执行,但您需要手动调用其他委托(通过 XAML 与该事件挂钩),这可以像这样实现 -

public event TextCompositionEventHandler TextInputLinked = (sender, args) =>
{
   MyTextBox textBox = (MyTextBox)sender;
   if (textBox.TextInputLinked != null)
   {
       foreach (var handler in textBox.TextInputLinked.GetInvocationList())
       {
          if (handler.Target != null) <-- Check to avoid Stack overflow exception
          {
             handler.DynamicInvoke(sender, args);
          }
       }
   }
};

public MyTextBox()
{
    this.AddHandler(TextBox.TextInputEvent, TextInputLinked, true);
}

现在将根据需要调用其他处理程序。

【讨论】:

  • 难以置信!!这是完美的工作!我想我理解了这段代码,但是我需要更多地研究事件,我从未见过很多方法,例如GetInvocationListDynamicInvoke,这也是我第一次使用AddHandler。非常感谢!
  • 很高兴帮助 Lai32290.. :)
猜你喜欢
  • 2013-08-15
  • 1970-01-01
  • 2015-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多