2012-11-23 180 views
0

我已经添加了一个扩展的WPF Toolkit DoubleUpDown控件。 行为是,如果你输入5.35就没问题。 然后说你键入4.3errortext7和选项卡它恢复到5.35(因为4.3errortext7不是一个有效的数字)。扩展的WPF工具包DoubleUpDown

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

回答

1

我能够拿出最好的是使用PreviewTextInput事件,并检查是否有有效的输入,不幸的是它将使仍然允许数字之间的空间,但会阻止所有其他的文本被输入。

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

} 
+0

是啊,我一直在寻找的是为好,但我认为他们可能是一个方式做一次,所以我们没必要到处代码添加了控制。 – DermFrench

0

也许有点晚了,但我有同样的问题昨天我也不想每次使用控件时都注册一个处理程序,我把这个解决方案混合在一起与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> 
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)); 
    } 
相关问题