在我的 WPF 应用程序中,我有一个 TextBox,用户可以在其中输入一个百分比(作为 int,介于 1 和 100 之间)。 Text 属性是数据绑定(bind)到 ViewModel 中的一个属性的,在该属性中我强制该值在 setter 中的给定范围内。
但是,在 .NET 3.5 中,数据在被强制后无法在 UI 中正确显示。在 this post on MSDN , WPF 博士指出您必须手动更新绑定(bind),以便显示正确的绑定(bind)。因此,我有一个 TextChanged
调用 UpdateTarget()
的处理程序(在 View 中) .在代码中:
查看 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();
}
View 模型:
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)。具体来说,在我第一次强制该值之后,只要我继续输入整数值(因为我绑定(bind)到一个 int),TextBox 就会忽略任何进一步的强制值。
因此,如果我输入“123”,在 3 之后我会看到值“100”。现在,如果我输入“4”,ViewModel 中的 setter 将获取值“1004”,它强制为 100。然后触发 TextChanged 事件(并且发送者的 TextBox.Text 为“100”!),但 TextBox 显示“1004”。如果我然后输入“5”,setter 将获得值“10045”等。
如果我然后输入“a”,TextBox 会突然显示正确的值,即“100”。如果我继续输入数字直到 int 溢出,也会发生同样的情况。
我怎样才能解决这个问题?
最佳答案
尝试在 xaml 中使用 Explicit 而不是 PropertyChanged:
<TextBox Text="{Binding Percentage, Mode=TwoWay, UpdateSourceTrigger=Explicit, TargetNullValue={x:Static System:String.Empty}}"
TextChanged="TextBox_TextChanged" />
在 UpdateSource 而不是 UpdateTarget 后面的代码中
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
// Removed safe casts and null checks
((TextBox)sender).GetBindingExpression(TextBox.TextProperty).UpdateSource();
}
对其进行了测试,并且可以正常工作。
顺便说一句,这个问题可能会在更高版本的 .NET 中得到解决。
关于.net - 强制 WPF 文本框在 .NET 4.0 中不再工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3905227/