Dan*_*ose 5 .net data-binding wpf wpf-4.0
在我的WPF应用程序中,我有一个TextBox,用户可以在其中输入百分比(int,介于1和100之间).Text属性数据绑定到ViewModel中的属性,在此处我将值强制置于setter中的给定范围内.
但是,在.NET 3.5中,强制后,UI中的数据无法正确显示.在MSDN上的这篇文章中,WPF博士表示您必须手动更新绑定,以便显示正确的内容.因此,我有一个TextChanged调用处理程序(在View中)UpdateTarget().在代码中:
查看XAML:
<TextBox Text="{Binding Percentage, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, TargetNullValue={x:Static sys:String.Empty}}"
TextChanged="TextBox_TextChanged"/>
Run Code Online (Sandbox Code Playgroud)
查看代码隐藏:
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
// Removed safe casts and null checks
((TextBox)sender).GetBindingExpression(TextBox.TextProperty).UpdateTarget();
}
Run Code Online (Sandbox Code Playgroud)
视图模型:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,这个代码在.NET 4.0中断了(相同的代码,只是将TargetFramework更改为4.0).具体来说,在我第一次强制该值之后,只要我继续输入整数值(因为我绑定到int),TextBox就会忽略任何进一步的强制值.
所以如果我输入"123",在3之后我看到值"100".现在,如果我输入"4",ViewModel中的setter获取值"1004",它强制为100.然后TextChanged事件触发(并且发送者的TextBox.Text为"100"!),但TextBox显示" 1004" .如果我然后输入"5",则setter获取值"10045"等.
如果我然后输入"a",突然TextBox显示正确的值,即"100".如果我继续输入数字直到int溢出,则会发生同样的情况.
我怎样才能解决这个问题?
小智 4
尝试在 xaml Explicit 中使用而不是 PropertyChanged:
<TextBox Text="{Binding Percentage, Mode=TwoWay, UpdateSourceTrigger=Explicit, TargetNullValue={x:Static System:String.Empty}}"
TextChanged="TextBox_TextChanged" />
Run Code Online (Sandbox Code Playgroud)
并在 UpdateSource 而不是 UpdateTarget 后面的代码中
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
// Removed safe casts and null checks
((TextBox)sender).GetBindingExpression(TextBox.TextProperty).UpdateSource();
}
Run Code Online (Sandbox Code Playgroud)
测试了一下,它有效。顺便说一句,这个问题可能会在.NET 的更高版本中得到解决。
| 归档时间: |
|
| 查看次数: |
3384 次 |
| 最近记录: |