用文本框编写文本的数据验证,MVVM c#
本文关键字:文本 验证 数据 MVVM | 更新日期: 2023-09-27 18:08:07
我制作了一个应用程序,我喜欢在文本框中写入一些字节。我喜欢验证是否真正的HEX代码写入文本框或不提醒用户,如果没有。
我从来没有在MVVM和XAML中做过这个。怎么做呢?我在网上找到了几个教程,但问题是我喜欢写64字节。我有64个文本框拉在一起在一个数组。
其中一个文本框:
<TextBox Text="{Binding TB[4], UpdateSourceTrigger=PropertyChanged}" Grid.Column="0" Grid.Row="0" Style="{StaticResource byteTextBoxStyle}"/>
和数组变量:
private string[] _tb = new string[64];
public string[] TB
{
get
{ return _tb; }
set
{
_tb = value;
NotifyPropertyChanged("TB");
}
}
目标是红色文本块在所有文本框的下面,并写一个红色(类似这样)。
我可以做到以后当按钮被按下-拉在一起数组在一个字符串和检查正则表达式是什么是不OK。但是我想要实时的,当用户输入文本并立即识别它是OK还是not。
请帮助,因为我是新的MVVM和WPF的东西。如有问题请提。谢谢!
我以前用system . windows . interactive .dll做过类似的事情
https://www.nuget.org/packages/System.Windows.Interactivity.WPF/如果键入非十六进制值,则终止按下键事件。
{
/// <summary>
/// Provides functionality to allow users to type only letters [0-9 A-F a-f].
/// </summary>
public class HexEditTextBox : TriggerAction<DependencyObject>
{
protected override void Invoke(object parameter)
{
var textBox = this.AssociatedObject as TextBox;
if (textBox != null) textBox.PreviewKeyDown += HandlePreviewKeyDownEvent;
}
/// <summary>
/// Checks whether the input is a valid key for a Hex number.
/// Sets the 'Handled' Property as True if the input is invalid, so that further actions will not be performed for this Action.
/// </summary>
/// <param name="sender"></param>
/// <param name="e">KeyEventArgs instance</param>
private void HandlePreviewKeyDownEvent(object sender, KeyEventArgs e)
{
var acceptedKeys = new List<Key>()
{
Key.D0, Key.D1, Key.D2, Key.D3,Key.D4,Key.D5,Key.D6,Key.D7,Key.D8,Key.D9,
Key.A,Key.B,Key.C,Key.D,Key.E,Key.F,
Key.Tab,Key.Back,Key.Delete,Key.Left,Key.Right,Key.Up,Key.Down,Key.Enter,Key.Home,Key.End,
Key.NumPad0,Key.NumPad1,Key.NumPad2,Key.NumPad3,Key.NumPad4,Key.NumPad5,Key.NumPad6,Key.NumPad7,Key.NumPad8,Key.NumPad9
};
e.Handled = !acceptedKeys.Contains(e.Key);
}
}
}
您应该能够在这里插入验证