【发布时间】:2014-03-10 17:49:13
【问题描述】:
我正在使用 .NET 4.0。我有一些非常简单的代码,可以让用户输入 1 到 99,999(含)之间的数字。我在属性设置器中有一些逻辑,如果它不符合业务规则(例如,它不是数字或数字太大),则阻止应用最新值。
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}"/>
谁能告诉我我做错了什么?
我已经阅读了很多与此非常相似的问题,但没有一个答案对我有用。奇怪的是,当我不根据数字进行验证,而只是将输入的所有文本更改为大写时,它工作得很好。当我尝试不将属性设置为新值时,它似乎不起作用。
【问题讨论】:
标签: c# wpf .net-4.0 inotifypropertychanged