1

有一个我想限制输入范围的文本框。
在这个简单的例子中,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");
        }
    }
}
4

2 回答 2

3

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

即使在您提出 NotifyPropertyChanged 之后,我想因为您正处于绑定操作的中间,目标不会得到更新。

您可以通过删除UpdateSourceTrigger并将其保留为默认值 ( LostFocus) 来解决此问题。只要您在用户标签退出后对它感到满意,这样做就会起作用。

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

(Mode=TwoWay 是 TextBox 的默认设置,因此您也可以将其删除)。

如果您想在每次按键时对其进行评估,我建议您查看蒙面编辑,并处理按键/按键,以防止将值输入到 中TextBox,而不是在输入后尝试更改它们。

于 2013-03-06T19:40:31.800 回答
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 :)

于 2013-03-06T21:08:03.233 回答