OnPropertyChanged上的WPF TextBox值不会更改

jps*_*res 6 wpf binding textbox mvvm

我有一个TextBox,其Value绑定到ViewModel属性:

        <TextBox Name="txtRunAfter" Grid.Column="4" Text="{Binding Mode=TwoWay, Path=RunAfter}" Style="{StaticResource TestStepTextBox}"/>
Run Code Online (Sandbox Code Playgroud)

set和get工作正常,直到我设置Value时添加一些验证:

    private int _runAfter = 0;
    public string RunAfter
    {
        get
        {
            return _runAfter.ToString();
        }

        set
        {
            int val = int.Parse(value);

            if (_runAfter != val)
            {
                if (val < _order)
                    _runAfter = val;
                else
                {
                    _runAfter = 0;
                    OnPropertyChanged("RunAfter");
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

虽然已达到OnPropertyChanged(我已经相同),但视图不会更改.我怎样才能做到这一点?

谢谢,JoséTavares

Abe*_*cht 5

问题是您正在更新您的属性Binding时更新源Binding.WPF PropertyChanged在响应Binding更新时引发事件时实际上不会检查您的属性值.您可以通过使用Dispatcher延迟事件在该分支中的传播来解决此问题:

set
{
    int val = int.Parse(value);

    if (_runAfter != val)
    {
        if (val < _order)
        {
            _runAfter = val;
            OnPropertyChanged("RunAfter");
        }
        else
        {
            _runAfter = 0;
            Dispatcher.CurrentDispatcher.BeginInvoke(
                new Action<String>(OnPropertyChanged), 
                DispatcherPriority.DataBind, "RunAfter");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:

我注意到的另一件事是BindingTextBox正在使用默认值UpdateSourceTrigger,这是在TextBox失去焦点时发生的.在TextBox使用此模式失去焦点之前,您将看不到文本更改回0 .如果将其更改为PropertyChanged,您将立即看到这种情况.否则,在您TextBox失去焦点之前,您的财产将不会被设置:

<TextBox Name="txtRunAfter" Grid.Column="4" Text="{Binding RunAfter, UpdateSourceTrigger=PropertyChanged}" Style="{StaticResource TestStepTextBox}"/>
Run Code Online (Sandbox Code Playgroud)