1

I'm looking for a way to retrieve and force user to enter an int value in a WPF application (developed in C#).

What is the best way to do it ? I've seen "TextBox" can do the Job with value parsing, but i wonder if there is a better way to do it with another WPF control (other than a TextBox) to help user to do so more easily (with up or down button to increment or decrement for example) ?

Goal is to simplify user experience by "guiding" him during "value" selection

Dharman
  • 30,962
  • 25
  • 85
  • 135
Gecko
  • 27
  • 3
  • 1
    I'm not a WPF guy, but you can implement validation rules on a text box (directly in the XAML) – Flydog57 Jul 01 '20 at 20:09
  • 1
    The easiest and (IMHO) recommended opinion is "make it clear it must take a number". And with "make it clear" I'm talking about the description of the textbox (tooltip, label, whatever...) and the validation of the textbox (see more, validation: https://www.c-sharpcorner.com/UploadFile/tirthacs/inotifydataerrorinfo-in-wpf/), in the other hand, there another option "violating the pure concept" of MVVM: https://stackoverflow.com/questions/1268552/how-do-i-get-a-textbox-to-only-accept-numeric-input-in-wpf – DrkDeveloper Jul 01 '20 at 20:09
  • Simply use `Binding` to the Property of type `int`. Validation will be performed automatically. User will see red stroke for invalid value. – aepot Jul 01 '20 at 21:17

1 Answers1

1

Just for you, I've quickly wrote this. This isn't the most efficient way of doing this also you can implement more validations like for decimal numbers or non-negative numbers. Also you can make TexBox IsReadOnly = true to make sure user don't input any non-numeric values.

You can do a lot of the things ! this is just to give you an idea.

XAML

<StackPanel Orientation="Horizontal" Width="200" VerticalAlignment="Center" HorizontalAlignment="Center">
    <TextBox x:Name="NumberBox" VerticalAlignment="Center" Width="120" Text="0"></TextBox>
    <StackPanel Orientation="Vertical" VerticalAlignment="Center" 
                Margin="2 0 0 0" Spacing="1">
        <Button x:Name="UpBtn" Width="50" Height="25" Click="IncrementDecrement">▲</Button>
        <Button x:Name="DownBtn" Width="50" Height="25"  Click="IncrementDecrement">▼</Button>
    </StackPanel>
</StackPanel>  

Back-End Code (non MVVM WAY)

private void IncrementDecrement(object sender, RoutedEventArgs e)
{
    var senderBtn = sender as Button;
    var value = NumberBox.Text.Trim();
    if (string.IsNullOrEmpty(value))
    {
        value = 0.ToString();
    }
    bool success = Int32.TryParse(value, out var number);
    if (!success)
    {
        // show error
        return;
    }

    NumberBox.Text = senderBtn.Name == "UpBtn" ? (++number).ToString() : (--number).ToString();
}  

Result

enter image description here

Hammas
  • 1,126
  • 1
  • 12
  • 37