0

I am working on a WPF aplication with MVVM pattern. I created a button and a textbox and binded them so when i write in the textbox and press the button, a message will with the content of the textbox will appear. Now i want to allow only hexadecimals in the textbox. Any ideeas ?

 this.checkme = new SimpleCommand(this.CanCheckMe, this.IsCheckMe);//initialize commands

 private Boolean IsCheckMe()//methods
    {
        return true;
    }

 private void CanCheckMe()
    {
        MessageBox.Show(this.Numbers);
    }
 private readonly SimpleCommand checkme;
 private string numbers;
public String Numbers
    {
        get { return numbers; }
        set {


            if (numbers == value)

                return;
            this.numbers = value;
            this.OnPropertyChanged(nameof(Numbers));

            }
The above are the code for the button and the textbox in c# and below is the code in xaml.
<ribbon:TextBox Header="Numbers" Text="{Binding Path=Numbers, UpdateSourceTrigger=PropertyChanged, NotifyOnSourceUpdated=True}"/>
    <ribbon:Button Header="Check me" Command="{Binding Path=CheckMe}"/>
  • _"Now i want to allow only hexadecimals in the textbox"_ - Does that mean you want to restrict the input to accept only Hex-Digits or do you want to _validate_ input for Hex Numbers? Or both? – Fildor Aug 16 '21 at 08:53
  • I wanna do both – Razvan Razvi Aug 16 '21 at 08:55
  • The problem in the prince is solved in two ways: the first is at the View level by listening for the TextChanged event or (less often) the PreviewTextInput event. The second way is to add an additional string property to the ViewModel that contains a numeric property representation. Search the forum for the phrase "input only numbers in the TextBox". Here is one of them: https://stackoverflow.com/questions/1268552/how-do-i-get-a-textbox-to-only-accept-numeric-input-in-wpf You can change the solutions used in them to suit your task. If you yourself cannot make these changes - write about it. – EldHasp Aug 16 '21 at 09:47
  • Hexadecimals include letters so limiting to numbers is not really sufficient. You could handle this in the textchanged event or a binding validationrule. Your textchanged could go in a behaviour. I would be inclined to go with validationrule myself. You can validate using tryparse. There's a parameter to specify hexadecimal https://stackoverflow.com/questions/2801509/uint32-tryparse-hex-number-not-working – Andy Aug 16 '21 at 10:34

1 Answers1

1

Numbers should not be a string type. Number should be an Integer as it will store a number.

private int numbers;
public int Numbers
{
    get { return numbers; }
    set {
          if (numbers == value)
            return;
          this.numbers = value;
          this.OnPropertyChanged(nameof(Numbers));
        }
}

and the binding like this will display nthe int value as hex:

<TextBox Text="{Binding Path=Numbers,StringFormat={}0x{0:X8}"/>

if you want to validate the users input you will need a binding converter like this:

 public class ToHex : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            try
            {
                return "0x" + System.Convert.ToInt32(value).ToString("X");

            }
            catch (Exception)
            {
                return value;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            try
            {
                return Int32.Parse(value.ToString().Replace("0x", ""), System.Globalization.NumberStyles.HexNumber);

            }
            catch (Exception)
            {
                return value;
            }
        }
    }

and the XAML:

<local:ToHex x:Key="ToHex"/>
<TextBox Text="{Binding Path=Numbers, Converter={StaticResource ToHex}}"/>
Denis Schaf
  • 2,478
  • 1
  • 8
  • 17
  • Your answer is not relevant to the question of the topic. Question: "Now i want to allow only hexadecimals in the textbox". There is no question about how to create a property. The hexadecimal string format would help if you only needed the input of numbers. It can in no way prohibit the input of incorrect letters. In your XAML, you specified "TextBlock", and in the question TC is wrote "TextBox". – EldHasp Aug 16 '21 at 09:18
  • This is already better, but in principle it still does not solve the TC problem. To implement the full algorithm, in the reverse assignment (from the target to the source), it is necessary to check the correctness of converting the string to a number, in case of incorrectness, return to the previous value of the number, if correct, the comparison with the current value of the number, if they are not equal, then change it. For direct assignment, you need to convert a string to a number, compare this number with the number in the property, if they are not equal, then change the string. – EldHasp Aug 16 '21 at 09:35
  • It is impossible to do this all by using the converter alone. This logic can be implemented either in the TextChanged event or in the ViewModel using an additional string property to represent the number. An example of the second implementation option, if you speak Russian, you can see here: https://www.cyberforum.ru/wpf-silverlight/thread2863534.html#post15652779 – EldHasp Aug 16 '21 at 09:35