Joshua LI
Joshua LI

Reputation: 4733

Only allow to input at least 1-digit and at most 2-digit number in DecimalUpDown in WPF

I use DecimalUpDown in xctk for user to input at least 1-digit and at most 2-digit number.

enter image description here

The xaml code in shown below.

<xctk:IntegerUpDown Name="hourBox" Margin="0,0,0,1" ShowButtonSpinner="False" Text="0" 
                    Grid.Row="0" Maximum="50" Minimum="0" ClipValueToMinMax="True"
                    FontSize="22" TextAlignment="Center" PreviewTextInput="PreviewNumInput"/>

The following code is for PreviewTextInput:

private void PreviewNumInput(object sender, TextCompositionEventArgs e) 
{
    if (!IsPositiveNum(e.Text))
        e.Handled = true;
}

private bool IsPositiveNum(string str) 
{
    int x;
    if (int.TryParse(str, out x) && x >= 0)
        return true;
    return false;
}

How can I allow user to only input at least 1-digit and at most 2-digit number between 0 and 50 before value clipping on out-focus?

For example:

0
15
48
50
86   (Not Allowed)
123  (Not Allowed)


References


Upvotes: 0

Views: 542

Answers (2)

Joshua LI
Joshua LI

Reputation: 4733

private void hourBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    IntegerUpDown senderTBox = sender as IntegerUpDown;
    TextBox tempTBox = senderTBox.Template.FindName("PART_TextBox", senderTBox) as TextBox;
    string text = tempTBox.CaretIndex > 0 ? senderTBox.Text + e.Text : e.Text + senderTBox.Text;
    if (senderTBox.Text.Length == 2)
    {
        senderTBox.Text = "";
        e.Handled = false;
        return;
    }
    e.Handled = !(IsPositiveNumInRange(text, 0, 99) && text.Length <= 2);
}

private void PreviewNumInput(object sender, TextCompositionEventArgs e)
{
    TextBox textBox = hourBox.Template.FindName("PART_TextBox", hourBox) as TextBox;
    string text = textBox.CaretIndex > 0 ? hourBox.Text + e.Text : e.Text + hourBox.Text;
    e.Handled = !IsPositiveNumInRange(text, 0, 99);
}

Upvotes: 0

mm8
mm8

Reputation: 169200

You could just modify your code slightly:

private void PreviewNumInput(object sender, TextCompositionEventArgs e)
{
    TextBox textBox = hourBox.Template.FindName("PART_TextBox", hourBox) as TextBox;
    string text = textBox.CaretIndex > 0 ? hourBox.Text + e.Text : e.Text + hourBox.Text;
    e.Handled = !IsPositiveNum(text);
}

private bool IsPositiveNum(string str)
{
    int x;
    if (int.TryParse(str, out x) && x >= 0 && x <= 50)
        return true;
    return false;
}

Upvotes: 1

Related Questions