Display Name
Display Name

Reputation: 458

TextBox does not Update when Text is the same

I have a TextBox. The TextBox is binded to a Property. The Property will be set each time I type a character into the Box. That works perfect!

Now I want to remove invalid characters when they are typed in.

For example: The user typed @ and @ is not allowed so it will be removed (something like string.replace("@", "");.

That also works fine. The old Text is, lets say "6378fj". Now someone types @. The new Text, 6378@fj, will be sent to the Property, the @ will be removed (now its 6378fj) and OnPropertyChanged will be fired.

Now the TextBox gets the new Value from the Property, but it's now the same value as before. And the @still remains in The TextBox. It's a bit strange, ans it only works when the Validated Text is the same as the original Text.

Is there a way to let the TextBox update itself? I hope you know what I mean, I'm not a native English speaker. Thanks.

Upvotes: 0

Views: 325

Answers (5)

Sender
Sender

Reputation: 6858

String str1 = "Hello";
String str2 = "Hello";
bool ch = str1 == str2;

Upvotes: 0

Anthony
Anthony

Reputation: 165

Why don't you want deny input of symbols like '@'? I think it'll be easier than searching these symbols and its deleting...

In this case you can use PreviewTextInput event.

Upvotes: 0

ZombieSheep
ZombieSheep

Reputation: 29963

Silly question, but you say you are doing string.Replace("@",""). You are remembering to assign the result back to your original string, aren't you? I know it is an obvious question, but I have seen it too many times to not mention it here. :)

ie. myString = myString.Replace("@","");

Upvotes: 0

Samuel Slade
Samuel Slade

Reputation: 8623

You may find it easier to perform validation on the text entered into the TextBox by handling the PreviewTextInput event. This will allow you to check the new text before it is committed to the TextBox. If you wish to prevent the edit, you can use e.Handled = true on the TextCompositionEventArgs passed into the event handler.

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292725

I assume you're replacing the character in the setter of the property? If the property is being updated by the binding, the PropertyChanged event for that property is ignored. You need to raise the event after the binding has finished updating the property. An easy way to do that is to use the Dispatcher.BeginInvoke method:

Application.Current.Dispatcher.BeginInvoke(new Action(() => OnPropertyChanged("TheProperty")));

Upvotes: 1

Related Questions