扩展的WPF工具包DoubleUpDown

时间:2012-11-23 17:05:32

标签: wpf xaml

我添加了一个Extended WPF Toolkit DoubleUpDown控件。 行为是如果你输入5.35就可以了。 然后说你键入4.3errortext7并将其恢复为5.35(因为4.3errortext7不是有效数字)。

但是在这种情况下我只想转到4.37(并忽略无效字符。 是否有一种优雅的方式来获得我所需要的行为?

3 个答案:

答案 0 :(得分:1)

我能想到的最好的方法是使用PreviewTextInput事件并检查有效输入,不幸的是它仍允许在数字之间留出空格,但会阻止输入所有其他文本。

private void doubleUpDown1_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    if (!(char.IsNumber(e.Text[0]) || e.Text== "." ))
    {
        e.Handled = true;
    }

}

答案 1 :(得分:0)

也许有点晚了但我昨天遇到了同样的问题,而且每次使用控件时我都不想注册处理程序。我将Mark Hall的解决方案与Attached Behavior混合在一起(灵感来自这篇文章:http://www.codeproject.com/Articles/28959/Introduction-to-Attached-Behaviors-in-WPF):

public static class DoubleUpDownBehavior
{
    public static readonly DependencyProperty RestrictInputProperty = 
         DependencyProperty.RegisterAttached("RestrictInput", typeof(bool),
             typeof(DoubleUpDownBehavior), 
         new UIPropertyMetadata(false, OnRestrictInputChanged));

    public static bool GetRestrictInput(DoubleUpDown ctrl)
    {
        return (bool)ctrl.GetValue(RestrictInputProperty);
    }

    public static void SetRestrictInput(DoubleUpDown ctrl, bool value)
    {
        ctrl.SetValue(RestrictInputProperty, value);
    }

    private static void OnRestrictInputChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
    {
        DoubleUpDown item = depObj as DoubleUpDown;
        if (item == null)
            return;

        if (e.NewValue is bool == false)
            return;

        if ((bool)e.NewValue)
            item.PreviewTextInput += OnPreviewTextInput;
        else
            item.PreviewTextInput -= OnPreviewTextInput;
    }

    private static void OnPreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        if (!(char.IsNumber(e.Text[0]) || 
           e.Text == CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator))
        {
            e.Handled = true;
        }
    }
}

然后您可以像这样设置DoubleUpDown的默认样式:

<Style TargetType="xctk:DoubleUpDown">
    <Setter Property="behaviors:DoubleUpDownBehavior.RestrictInput" Value="True" /> 
</Style>

答案 2 :(得分:0)

就我而言,使用正则表达式要好得多。

  private void UpDownBox_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        var upDownBox = (sender as DoubleUpDown);
        TextBox textBoxInTemplate = (TextBox)upDownBox.Template.FindName("PART_TextBox", upDownBox);
        Regex regex = new Regex("^[.][0-9]+$|^[0-9]*[.]{0,1}[0-9]*$");
        e.Handled = !regex.IsMatch(upDownBox.Text.Insert((textBoxInTemplate).SelectionStart, e.Text));
    }
相关问题