WPF文本框的值不会改变OnPropertyChanged [英] WPF TextBox value doesn't change on OnPropertyChanged

查看:1183
本文介绍了WPF文本框的值不会改变OnPropertyChanged的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本框,其值是绑定到一个ViewModel属性:

I have a TextBox whose Value is binded to a ViewModel property:

        <TextBox Name="txtRunAfter" Grid.Column="4" Text="{Binding Mode=TwoWay, Path=RunAfter}" Style="{StaticResource TestStepTextBox}"/>

设置和直到我尝试添加时,该值设置一些验证得到了工作的罚款:

The set and get were working fine until I tried to add some validation when the Value is set:

    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");
                }
            }
        }
    }

虽然达到OnPropertyChanged(我dubugged了),视图不会改变。
我怎样才能使这项工作?

Although the OnPropertyChanged is reached (I have dubugged that), the View is not changed. How can I make this work?

谢谢,
何塞·塔瓦雷斯

Thanks, José Tavares

推荐答案

的问题是,在更新源中的绑定,而结合正在更新你的财产。 WPF实际上不会检查你的财产的价值时,它提出了一个的PropertyChanged 事件响应绑定更新。您可以通过使用调度延迟事件的传播中的一个分支,解决这个问题:

The problem is that you are updating the source for the Binding while the Binding is updating your property. WPF won't actually check your property value when it raises the PropertyChanged event in response to a Binding update. You can solve this by using the Dispatcher to delay the propagation of the event in that branch:

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");
        }
    }
}

更新:

我注意到的另一件事是,绑定文本框使用默认 UpdateSourceTrigger ,它发生在当文本框失去焦点。你不会看到文字变回0,直到文本框后失去焦点,与此模式。如果您将其更改为的PropertyChanged ,你会看到这个立即发生。否则,你的财产将不会被置直到你的文本框失去焦点:

The other thing I noticed is that the Binding on your TextBox is using the default UpdateSourceTrigger, which happens when the TextBox loses focus. You won't see the text change back to 0 until after the TextBox loses focus with this mode. If you change it to PropertyChanged, you will see this happen immediately. Otherwise, your property won't get set until your TextBox loses focus:

<TextBox Name="txtRunAfter" Grid.Column="4" Text="{Binding RunAfter, UpdateSourceTrigger=PropertyChanged}" Style="{StaticResource TestStepTextBox}"/>

这篇关于WPF文本框的值不会改变OnPropertyChanged的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆