C# WPF文本框中的必填字段验证
我需要一个简单的方法来验证文本框的有效性(必填字段)。当用户按下按钮时,应检查所有必填字段是否存在 我尝试过以下代码:C# WPF文本框中的必填字段验证,c#,wpf,validation,textbox,C#,Wpf,Validation,Textbox,我需要一个简单的方法来验证文本框的有效性(必填字段)。当用户按下按钮时,应检查所有必填字段是否存在 我尝试过以下代码: <Window.Resources> <ControlTemplate x:Key="validationTemplate"> <DockPanel> <TextBlock Foreground="Red" FontSize="25" Text="*" DockPanel.Dock="Ri
<Window.Resources>
<ControlTemplate x:Key="validationTemplate">
<DockPanel>
<TextBlock Foreground="Red" FontSize="25" Text="*" DockPanel.Dock="Right" />
<AdornedElementPlaceholder/>
</DockPanel>
</ControlTemplate>
</Window.Resources>
<Grid>
<Button Content="Button" HorizontalAlignment="Left" Height="26" Margin="62,213,0,0" VerticalAlignment="Top" Width="121" Click="Button_Click_1"/>
<TextBox x:Name="txtEmail1" Text="" Height="61" Margin="116,10,194,0" Validation.ErrorTemplate="{StaticResource validationTemplate}"/>
</Grid>
请任何人建议一种在WPF的文本框中进行验证的方法。
谢谢您应该将
文本框
的文本
属性绑定到视图模型的属性,并在视图模型类中实现IDataErrorInfo
接口
请参考以下示例代码
代码:
public partial class Window3 : Window
{
Window3ViewModel viewModel = new Window3ViewModel();
public Window3()
{
InitializeComponent();
DataContext = viewModel;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
viewModel.Validate();
}
}
public class Window3ViewModel : INotifyDataErrorInfo
{
private readonly Dictionary<string, string> _validationErrors = new Dictionary<string, string>();
public void Validate()
{
bool isValid = !string.IsNullOrEmpty(_text);
bool contains = _validationErrors.ContainsKey(nameof(Text));
if (!isValid && !contains)
_validationErrors.Add(nameof(Text), "Mandatory field!");
else if (isValid && contains)
_validationErrors.Remove(nameof(Text));
if (ErrorsChanged != null)
ErrorsChanged(this, new DataErrorsChangedEventArgs(nameof(Text)));
}
public bool HasErrors => _validationErrors.Count > 0;
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
public IEnumerable GetErrors(string propertyName)
{
string message;
if (_validationErrors.TryGetValue(propertyName, out message))
return new List<string> { message };
return null;
}
private string _text;
public string Text
{
get { return _text; }
set
{
_text = value;
}
}
}
<Window x:Class="WpfApp2.Window3"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp2"
mc:Ignorable="d"
Title="Window3" Height="300" Width="300">
<Window.Resources>
<ControlTemplate x:Key="validationTemplate">
<DockPanel>
<TextBlock Foreground="Red" FontSize="25" Text="*" DockPanel.Dock="Right" />
<AdornedElementPlaceholder/>
</DockPanel>
</ControlTemplate>
</Window.Resources>
<Grid>
<Button Content="Button" HorizontalAlignment="Left" Height="26" Margin="62,213,0,0" VerticalAlignment="Top" Width="121" Click="Button_Click_1"/>
<TextBox x:Name="txtEmail1" Text="{Binding Text}" Height="61" Margin="116,10,194,0" Validation.ErrorTemplate="{StaticResource validationTemplate}"/>
</Grid>
</Window>
公共部分类窗口3:窗口
{
Window3ViewModel viewModel=新的Window3ViewModel();
公共窗口3()
{
初始化组件();
DataContext=viewModel;
}
私有无效按钮\u单击\u 1(对象发送者,路由目标)
{
viewModel.Validate();
}
}
公共类Window3ViewModel:INotifyDataErrorInfo
{
专用只读词典_validationErrors=新词典();
public void Validate()
{
bool isValid=!string.IsNullOrEmpty(\u text);
bool contains=_validationErrors.ContainsKey(nameof(Text));
如果(!isValid&&!contains)
_添加(nameof(Text),“必填字段!”);
else if(isValid&&contains)
_validationErrors.Remove(nameof(Text));
if(ErrorsChanged!=null)
ErrorsChanged(这是新数据errorschangedventargs(name of(Text)));
}
public bool HasErrors=>\u validationErrors.Count>0;
公共事件事件处理程序错误更改;
公共IEnumerable GetErrors(字符串propertyName)
{
字符串消息;
if(_validationErrors.TryGetValue(propertyName,输出消息))
返回新列表{message};
返回null;
}
私有字符串_文本;
公共字符串文本
{
获取{return\u text;}
设置
{
_文本=值;
}
}
}
XAML:
public partial class Window3 : Window
{
Window3ViewModel viewModel = new Window3ViewModel();
public Window3()
{
InitializeComponent();
DataContext = viewModel;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
viewModel.Validate();
}
}
public class Window3ViewModel : INotifyDataErrorInfo
{
private readonly Dictionary<string, string> _validationErrors = new Dictionary<string, string>();
public void Validate()
{
bool isValid = !string.IsNullOrEmpty(_text);
bool contains = _validationErrors.ContainsKey(nameof(Text));
if (!isValid && !contains)
_validationErrors.Add(nameof(Text), "Mandatory field!");
else if (isValid && contains)
_validationErrors.Remove(nameof(Text));
if (ErrorsChanged != null)
ErrorsChanged(this, new DataErrorsChangedEventArgs(nameof(Text)));
}
public bool HasErrors => _validationErrors.Count > 0;
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
public IEnumerable GetErrors(string propertyName)
{
string message;
if (_validationErrors.TryGetValue(propertyName, out message))
return new List<string> { message };
return null;
}
private string _text;
public string Text
{
get { return _text; }
set
{
_text = value;
}
}
}
<Window x:Class="WpfApp2.Window3"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp2"
mc:Ignorable="d"
Title="Window3" Height="300" Width="300">
<Window.Resources>
<ControlTemplate x:Key="validationTemplate">
<DockPanel>
<TextBlock Foreground="Red" FontSize="25" Text="*" DockPanel.Dock="Right" />
<AdornedElementPlaceholder/>
</DockPanel>
</ControlTemplate>
</Window.Resources>
<Grid>
<Button Content="Button" HorizontalAlignment="Left" Height="26" Margin="62,213,0,0" VerticalAlignment="Top" Width="121" Click="Button_Click_1"/>
<TextBox x:Name="txtEmail1" Text="{Binding Text}" Height="61" Margin="116,10,194,0" Validation.ErrorTemplate="{StaticResource validationTemplate}"/>
</Grid>
</Window>
我将向您展示如何使用IDataErrorInfo验证数据。此接口只有两个需要实现的成员:
公共字符串错误{get;}-获取一条错误消息,指示此对象的错误
public string this[string columnName]{get;}-获取具有给定名称的属性的错误消息。
实现IDataErrorInfo后,需要在要验证的元素中将ValidateSondaErrors设置为true。为了简化代码示例,我在MainViewModel中实现了IDataErrorInfo,如下所示:
public class MainViewModel : BindableBase, IDataErrorInfo
{
private string _firstName;
private string _lastName;
public string FirstName
{
get { return _firstName; }
set { _firstName = value; RaisePropertyChanged(); }
}
public string LastName
{
get { return _lastName; }
set { _lastName = value; RaisePropertyChanged(); }
}
public string this[string columnName]
{
get
{
string error = string.Empty;
switch (columnName)
{
case nameof(FirstName):
if (string.IsNullOrWhiteSpace(FirstName))
error = "First name cannot be empty.";
if (FirstName?.Length > 50)
error = "The name must be less than 50 characters.";
break;
case nameof(LastName):
if (string.IsNullOrWhiteSpace(LastName))
error = "Last name cannot be empty.";
break;
}
return error;
}
}
public string Error => string.Empty;
}
在文本框元素中,我将验证数据错误设置为真:
<TextBox Text="{Binding FirstName, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />