c# - 允许在文本框 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}"/>
解决方案
数字不应该是字符串类型。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}}"/>
推荐阅读
- tree - 小部件收音机在 one2many 行 odoo 中不起作用
- javascript - 如何将 json 对象下载为文件?
- python - 如何使用 pandas 从 excel 文件中获取单元格的背景颜色?
- jolokia - 无法访问 Jolokia JVM 代理
- docker - Docker Watchtower 有全局钩子机制吗?
- android - Android Json 处理问题
- angular - 使用放大凭据签署 HTTP 请求 - Angular
- javascript - 如何获取嵌套点击元素的值?
- reporting-services - SSRS 报告@To 参数
- highcharts - Highcharts Tooltip 显示不同的数据