UWP TextBox在输入时不尊重TwoWay绑定

Jac*_*ltz 9 c# textbox uwp

    <!-- 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));
        }
    }
Run Code Online (Sandbox Code Playgroud)

在TextBox中输入时,我希望它抛出任何无效字符(在这个示例中,字母'a',但它可能真的适用于任何东西).例如:

  1. 用户输入'fds'后跟'a'
  2. str检测到a,因此它不会将_str设置为'fdsa',将其保持在'fds',但无论如何都会引发事件以指示视图抛出'a'.
  3. 在WPF中,这会导致文本框中包含"fds".在UWP中,这会导致文本框仍然错误地包含"fdsa".

在UWP中,当控件具有焦点时,它似乎不会尊重TwoWay绑定.

我可以创建一个具有Click事件的按钮,按下该事件时将正确更新我的TextBox.

    private void btn_Click(object sender, RoutedEventArgs e)
    {
        OnPropertyChanged(nameof(str));
    }
Run Code Online (Sandbox Code Playgroud)

我们需要在WPF和UWP视图中使用许多ViewModel,并且我们在所有地方都有这种必需的行为.什么是这个问题的好方法?

*编辑*

周末之后又回到了问题,似乎已经解决了问题.我不知道为什么.我现在正在结束这个问题.

Bru*_*uim 1

您可以使用转换器来解决您的问题,您可以精心设计一个更好的转换器,在我的示例中,我只是使用一个愚蠢的转换器来演示我的想法。

转换器:

 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

XAML

<TextBox Text="{Binding Str, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource converter}}"/>
Run Code Online (Sandbox Code Playgroud)

您也可以使用附加行为。

  • 我之前注意到您发布的 WPF 答案与 WPF 无关。请尝试注意问题标签,这可以为每个人节省很多时间,包括您自己。 (2认同)