在我的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 …Run Code Online (Sandbox Code Playgroud)