首页 > 解决方案 > 允许在文本框 C# WPF 中使用十六进制

问题描述

我正在使用 MVVM 模式开发 WPF 应用程序。我创建了一个按钮和一个文本框并将它们绑定,所以当我在文本框中写入并按下按钮时,将出现一条包含文本框内容的消息。现在我想在文本框中只允许十六进制。有什么想法吗?

 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}"/>

标签: c#wpfmvvmdata-binding

解决方案


数字不应该是字符串类型。Number 应该是一个整数,因为它将存储一个数字。

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

并且像这样的绑定将 nthe int 值显示为十六进制:

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

如果您想验证用户输入,您将需要一个像这样的绑定转换器:

 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;
            }
        }
    }

和 XAML:

<local:ToHex x:Key="ToHex"/>
<TextBox Text="{Binding Path=Numbers, Converter={StaticResource ToHex}}"/>

推荐阅读