簡體   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