在我的WPF應用程序中,我有一個TextBox,用戶可以在其中輸入一個百分比(如int,介於1和100之間)。 Text屬性是綁定到ViewModel中的一個屬性的數據綁定,我強制該值在setter中的給定範圍內。強制一個WPF文本框不再在.NET 4.0中工作
但是,在.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"/>
查看隱藏代碼:
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」,則設置者獲得值「10045」等。
如果我然後輸入「a」,突然TextBox顯示正確的值,即「100」。如果我繼續輸入數字,直到int溢出,則會發生同樣的情況。
我該如何解決這個問題?