简体   繁体   中英

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: . For example, if I type on the key (lowercase) "a", I want the TextBox to print a (uppercase) "A" instead of (lowercase) "a".

My (partial) solution is, in my custom TextBox, to intercept the TextInput event by overloading the method OnPreviewTextInput . When this method is called, I receive a TextCompositionEventArgs whose Text property is "a".

So my first reflex would be updating this Text property to "A", as in the following code:

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.).

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)

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.

If you just need the uppercase scenario you can use the CharacterCasing property which does just that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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