简体   繁体   English

如何在恢复传播之前修改接收到的WPF路由事件arg参数的属性?

[英]How to modify a property of a received WPF routed event arg parameter before resuming its propagation?

I'm playing with a custom TextBox inheriting from the WPF TextBox, trying to learn about WPF events, so my problem is the following: When the TextBox receives an input, I want it to receive instead a case inverted version of this input . 我正在玩从WPF TextBox继承的自定义TextBox,试图了解WPF事件,所以我的问题如下: 当TextBox收到输入时,我希望它接收此输入的大小写反转版本 For example, if I type on the key (lowercase) "a", I want the TextBox to print a (uppercase) "A" instead of (lowercase) "a". 例如,如果我键入键(小写)“ a”,我希望文本框打印一个(大写)“ A”而不是(小写)“ a”。

My (partial) solution is, in my custom TextBox, to intercept the TextInput event by overloading the method OnPreviewTextInput . 我的(部分)解决方案是,在我的自定义TextBox中,通过重载方法OnPreviewTextInput来拦截TextInput事件。 When this method is called, I receive a TextCompositionEventArgs whose Text property is "a". 调用此方法时,我收到一个TextCompositionEventArgsText属性为“ a”。

So my first reflex would be updating this Text property to "A", as in the following code: 因此,我的第一个反应就是将此Text属性更新为“ A”,如以下代码所示:

protected override void OnPreviewTextInput(TextCompositionEventArgs e)
{
   e.Text = "A" ;
   base.OnPreviewTextInput(e) ;
}

The problem is that e.Text is readonly, and that I found no easy way to do that (and I searched, and I tweaked both the TextComposition and TextCompositionEventArgs , trying to construct one from zero, copying the data, etc.). 问题是e.Text是只读的,我发现没有简单的方法可以做到这一点(我进行了搜索,然后对TextCompositionTextCompositionEventArgs调整,试图从零构造一个,复制数据,等等)。

Did I miss something obvious? 我错过了明显的事情吗? Is there a way to do it? 有办法吗?

PS: The other solution was to use the WPF TextBox interface to tweak the result (retrieving the current .Text property, putting the inverted character inside, etc.), but this is not the desired solution as it bypasses completely the routed event generation/modification problem I'm trying to solve) PS:另一个解决方案是使用WPF TextBox接口调整结果(检索当前的.Text属性,将倒置的字符放入其中,等等),但这不是理想的解决方案,因为它完全绕过了路由事件的产生/我正在尝试解决的修改问题)

You can't change the event data. 您无法更改事件数据。 The events are there to notify you that something has happened or is happening and possibly let you cancel/handle it. 那里的事件可以通知您某些事情已经发生或正在发生,并可能使您取消/处理它。

In you case the best you can do is mark the event as Handled and then append the Text to the textbox yourself. 在这种情况下,最好的办法是将事件标记为Handled ,然后将Text附加到文本框。

If you just need the uppercase scenario you can use the CharacterCasing property which does just that. 如果只需要大写脚本,则可以使用CharacterCasing属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM