UWP TextBox Does Not Follow TwoWay Binding When Typing

<!-- View --> <TextBox Text="{Binding str, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/> // View Model private string _str; public string str { get { return _str; } set { if (!value.Contains("a")) _str = value; OnPropertyChanged(nameof(str)); } } 

When entering into a TextBox, I want it to throw out any invalid characters (in this example example, there was the letter "a", but it could be valid for anything). For example:

  • Custom type 'fds' followed by 'a'
  • str defines a, so it does not set _str to 'fdsa', storing it in 'fds', but in any case raises an event to indicate the view, to throw out 'a'.
  • In WPF, this causes the text box to contain "fds". In UWP, this causes the text box to contain “fdsa” incorrectly.

It seems that in UWP, when the control has focus, it will not honor the TwoWay binding.

I can create a button with a Click event, which when clicked will correctly update my TextBox.

  private void btn_Click(object sender, RoutedEventArgs e) { OnPropertyChanged(nameof(str)); } 

We have many ViewModels that we need to use in both WPF and UWP views, and we have this required behavior everywhere. What is a good solution to this problem?

* EDIT *

He returned to the problem after the weekend, and it seems that she fixed herself. I have no idea why. At the moment, I am closing the question.

+7
c # uwp textbox
source share
1 answer

You can use a converter to solve your problem, you can develop a better converter, in my example I just use a dumb converter to demonstrate my idea.

Converter

  public class Converter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value != null) { var someString = value.ToString(); return someString.Replace("a", ""); } return value; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return value; } } 

Xaml

 <TextBox Text="{Binding Str, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource converter}}"/> 

You can also use sticky behavior.

+1
source share

All Articles