0

Extended WPF Toolkit DoubleUpDown コントロールを追加しました。動作は、5.35 と入力すれば問題ありません。次に、4.3errortext7 と入力して Tab キーを押すと、5.35 に戻ります (4.3errortext7 は有効な数値ではないため)。

ただし、その場合は 4.37 に移行したいと思います (無効な文字を無視します。必要な動作を取得するエレガントな方法はありますか?

4

3 に答える 3

1

私が思いついた最善の方法は、PreviewTextInput イベントを使用して有効な入力を確認することです。残念ながら、数字の間にスペースを入れることはできますが、他のすべてのテキストを入力できないようにします。

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

}
于 2012-11-23T17:48:48.353 に答える
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));
    }
于 2015-05-08T15:30:44.807 に答える
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>
于 2014-10-09T17:11:36.623 に答える