在我的WPF应用程序中,我有一个TextBox,用户可以在其中输入一个百分比(整数,介于1和100之间)。文本属性被数据绑定到ViewModel中的属性,其中我强制设置器中的值在给定的范围内。
但是,在.NET 3.5中,数据在被强制后不能在UI中正确显示。在this post on MSDN中,Dr.WPF声明您必须手动更新绑定,才能显示正确的绑定。因此,我有一个调用UpdateTarget()
的TextChanged
处理程序(在视图中)。在代码中:
查看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();
}
ViewModel:
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)。具体地说,在我第一次强制取值之后,只要我继续输入整数值,TextBox就会忽略任何进一步的强制取值(因为我绑定到了一个整数)。
所以如果我输入"123",在3之后我看到的值是"100“。现在,如果我输入"4",ViewModel中的设置器将获得值"1004",它会强制将其设置为100。然后触发TextChanged事件(发送者的TextBox.Text是"100"!),但TextBox显示"1004“。如果我输入"5",设置器得到值"10045",依此类推。
如果我输入"a",TextBox会突然显示正确的值,即"100“。如果我继续输入数字,直到int溢出,也会发生同样的情况。
我该如何解决这个问题呢?
发布于 2010-10-11 18:43:52
尝试在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中得到解决。
发布于 2016-07-23 04:26:00
您可以使用PropertyChanged。但是,尝试绑定到EditValueProperty依赖项而不是TextProperty依赖项(或事件)。它将按预期工作。
https://stackoverflow.com/questions/3905227
复制相似问题