TextBox不尊重Get返回的值

时间:2013-03-06 19:08:57

标签: c# .net wpf binding textbox

有一个我想限制输入范围的TextBox 在这个简单的例子中,Int32从0到300 在现实生活中,范围更复杂,我不希望除了接收和显示有效值之外还涉及UI。

如果我输入333,则返回300并且300在TextBox中。

问题在于:
然后,如果我为3001添加一个数字,则该集合赋值为300 get被调用并返回300 但是3001仍然在TextBox中。

如果我粘贴3001,那么它会正确显示300 只有当一个键击使4个(或更多)数字失败时才会出现。

<TextBox Text="{Binding Path=LimitInt, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="60" Height="20"/>

public partial class MainWindow : Window, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }

    private Int32 limitInt = 0;

    public MainWindow()
    {
        InitializeComponent();
    }

    public Int32 LimitInt
    {
        get { return limitInt; }
        set
        {
            if (limitInt == value) return;
            limitInt = value;
            if (limitInt < 0) limitInt = 0;
            if (limitInt > 300) limitInt = 300; 
            NotifyPropertyChanged("LimitInt");
        }
    }
}

2 个答案:

答案 0 :(得分:3)

我相信这是因为您正在绑定操作的中间更改绑定源的值。当您在绑定上使用UpdateSourceTrigger=PropertyChanged时,您告诉它在每个按键上重新评估。在这种情况下,Binding正在将值推送到源,而不是尝试通过从源中提取来更新目标。

即使你提升了NotifyPropertyChanged,我想也是因为你正处于绑定操作的中间,目标并没有得到更新。

您只需移除UpdateSourceTrigger并将其保留为默认值(LostFocus)即可解决此问题。只要您在用户标签出来后发生这种情况,这样做就会有效。

<TextBox Text="{Binding Path=LimitInt}" Width="60" Height="20"/>

(Mode = TwoWay是TextBox的默认值,因此你也可以删除它。)

如果您想在每个按键上进行评估,我建议您查看屏蔽编辑,并处理按键/按键,以便您可以防止将值输入TextBox,而不是尝试在他们进入后改变它们。

答案 1 :(得分:1)

使用验证更好。

以下是:

定义您的XAML以检查PreviewTextInput

<TextBox Text="{Binding Path=LimitInt, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" PreviewTextInput="CheckNumberValidationHandler" Width="60" Height="20"/>

然后设置验证处理程序:

/// <summary>
/// Check to make sure the input is valid
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void CheckNumberValidationHandler(object sender, TextCompositionEventArgs e) {
    if(IsTextAllowed(e.Text)) {
    Int32 newVal;
    newVal = Int32.Parse(LimitInt.ToString() + e.Text);
    if(newVal < 0) {
        LimitInt = 0;
        e.Handled = true;
    }
    else if(newVal > 300) {
        LimitInt = 300;
        e.Handled = true;
    }
    else {
        e.Handled = false;
    }
    }
    else {
    e.Handled = true;
    }
}

/// <summary>
/// Check if Text is allowed
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
private static bool IsTextAllowed(string text) {
    Regex regex = new Regex("[^0-9]+");
    return !regex.IsMatch(text);
}

编辑:我检查过,它在.NET 4.0中有效:)

相关问题