强制WPF TextBox在.NET 4.0中不再起作用

时间:2010-10-11 10:09:45

标签: .net wpf data-binding wpf-4.0

在我的WPF应用程序中,我有一个TextBox,用户可以在其中输入百分比(int,介于1和100之间)。 Text属性数据绑定到ViewModel中的属性,在此处我将值强制置于setter中的给定范围内。

但是,在.NET 3.5中,强制后,UI中的数据无法正确显示。在this post on MSDN中,WPF博士表示您必须手动更新绑定,以便显示正确的内容。因此,我有TextChanged处理程序(在视图中)调用UpdateTarget()。在代码中:

查看XAML:

<TextBox Text="{Binding Percentage, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, TargetNullValue={x:Static sys:String.Empty}}"
    TextChanged="TextBox_TextChanged"/>

查看codebehind:

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),TextBox就会忽略任何进一步的强制值。

所以如果我输入“123”,在3之后我看到值“100”。现在,如果我输入“4”,ViewModel中的setter获取值“1004”,它强制为100.然后TextChanged事件触发(并且发送者的TextBox.Text为“100”!),但TextBox显示“ 1004" 。如果我然后输入“5”,则setter获取值“10045”等等。

如果我输入“a”,则TextBox突然显示正确的值,即“100”。如果我继续输入数字直到int溢出,则会发生同样的情况。

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

尝试使用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中得到解决。

答案 1 :(得分:0)

您可以使用PropertyChanged。但是,尝试绑定到EditValueProperty依赖项而不是TextProperty依赖项(或事件)。它将按预期工作。

相关问题