繁体   English   中英

当绑定属性强制执行某些业务规则时,绑定的WPF TextBox不会更新值

[英]Bound WPF TextBox is not updating value when the bound property enforces some business rules

我使用的是.NET 4.0。 我有一些非常简单的代码,允许用户输入1到99,999(含)之间的数字。 我在Property setter中有一些逻辑,如果它不遵守业务规则(例如,它不是数字或数字太大),则会阻止应用最新值。

    public class MainViewModel : INotifyPropertyChanged
{
    #region Fields

    private string _text = string.Empty;

    #endregion // Fields

    #region Properties

    public string Text
    {
        get { return _text; }

        set
        {
            if (_text == value) return;

            if (IsValidRange(value))
            {
                _text = value;
            }

            OnPropertyChanged("Text");
        }
    }

    #endregion // Properties

    #region Private Methods

    private bool IsValidRange(string value)
    {
        // An empty string is considered valid.
        if (string.IsNullOrWhiteSpace(value)) return true;

        // We try to convert to an unsigned integer, since negative bill numbers are not allowed,
        // nor are decimal places.
        uint num;
        if (!uint.TryParse(value, out num)) return false;

        // The value was successfully parse, so we know it is a non-negative integer.  Now, we
        // just need to make sure it is in the range of 1 - 99999, inclusive.
        return num >= 1 && num <= 99999;
    }

    #endregion // Private Methods

    #region INotifyPropertyChanged Implementation

    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }

    #endregion // INotifyPropertyChanged Implementation
}

我遇到的问题是,当值无效且我只是忽略该值时,绑定到此属性的TextBox不会更新以反映该更改; 相反,它只是保留输入的值。这是我如何绑定属性:

        <TextBox Grid.Row="0"
             Text="{Binding Path=Text, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>

谁能告诉我我做错了什么?

我已经阅读了很多与此类似的问题,但没有一个答案对我有用。 奇怪的是,当我不根据数字进行验证,只是将所有输入的文本更改为大写时,它就可以正常工作。 当我尝试不将Property设置为新值时,它似乎无效。

这似乎是.NET 3.5-4.0中TextBox一个错误。 我首先在4.5中尝试过这个,你的代码按照书面编写,但当我将项目转换为4.0时,我可以重现这个问题。 做了一些搜索后,我发现:

绑定到视图模型属性时WPF Textbox拒绝更新自身 ,该属性详细说明了引用的变通方法:

文本框与viewmodel属性不同步

当然如果您可以使用.NET 4.5我会建议,但当然并不总是那么容易。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM