在我的 WPF 应用程序中,我有一个文本框,用户可以在其中输入百分比(作为 int,介于 1 和 100 之间)。 Text 属性与 ViewModel 中的属性进行数据绑定,我在其中强制将值置于 setter 中的给定范围内。
但是,在 .NET 3.5 中,数据在强制后无法在 UI 中正确显示。在MSDN 上的这篇文章 http://social.msdn.microsoft.com/forums/en-US/wpf/thread/c404360c-8e31-4a85-9762-0324ed8812ef/,WPF 博士指出您必须手动更新绑定,以便显示正确的内容。因此,我有一个TextChanged
处理程序(在视图中)调用UpdateTarget()
。在代码中:
查看 XAML:
<TextBox Text="{Binding Percentage, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, TargetNullValue={x:Static sys:String.Empty}}"
TextChanged="TextBox_TextChanged"/>
查看隐藏代码:
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
// Removed safe casts and null checks
((TextBox)sender).GetBindingExpression(TextBox.TextProperty).UpdateTarget();
}
视图模型:
private int? percentage;
public int? Percentage
{
get
{
return this.percentage;
}
set
{
if (this.Percentage == value)
{
return;
}
// Unset = 1
this.percentage = value ?? 1;
// Coerce to be between 1 and 100.
// Using the TextBox, a user may attempt setting a larger or smaller value.
if (this.Percentage < 1)
{
this.percentage = 1;
}
else if (this.Percentage > 100)
{
this.percentage = 100;
}
this.NotifyPropertyChanged("Percentage");
}
}
不幸的是,此代码在 .NET 4.0 中中断(相同的代码,只是将 TargetFramework 更改为 4.0)。具体来说,在我第一次强制转换该值后,只要我继续输入整数值(因为我绑定到 int),文本框就会忽略任何进一步的强制转换值。
因此,如果我输入“123”,则在 3 之后我会看到值“100”。现在,如果我输入“4”,ViewModel 中的设置器将获取值“1004”,并将其强制为 100。然后触发 TextChanged 事件(发送者的 TextBox.Text 为“100”!),但 TextBox 显示“ 1004”。如果我输入“5”,设置器将获得值“10045”等。
如果我输入“a”,文本框会突然显示正确的值,即“100”。如果我继续输入数字直到 int 溢出,也会发生同样的情况。
我怎样才能解决这个问题?