在没有MVVM模式的情况下验证wpf
本文关键字:情况下 验证 wpf 模式 MVVM | 更新日期: 2023-09-27 18:21:04
我正在使用WPF,并使用代码隐藏文件绑定DataContext。我没有遵循MVVM或任何其他模式。我想在表单中添加验证。我使用了数据System.ComponentModel.DataAnnotations进行验证。以下是代码文件
[PropertyChanged.ImplementPropertyChanged]
public class Person : PropertyValidateModel
{
public long Id { get; set; }
[Required]
public string Name { get; set; }
public long Score { get; set; }
}
[PropertyChanged.ImplementPropertyChanged]
public abstract class PropertyValidateModel : IDataErrorInfo
{
// check for general model error
public string Error { get { return null; } }
// check for property errors
public string this[string columnName]
{
get
{
var validationResults = new List<ValidationResult>();
if (Validator.TryValidateProperty(
GetType().GetProperty(columnName).GetValue(this)
, new ValidationContext(this)
{
MemberName = columnName
}
, validationResults))
return null;
return validationResults.First().ErrorMessage;
}
}
}
我的XAML文件如下:
<Window x:Class="WPFDataContext.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel HorizontalAlignment="Left">
<TextBox Width="100" Text="{Binding Path=Name, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"></TextBox>
<TextBox Width="100" Text="{Binding Path=Score, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"></TextBox>
<Button Name="btnSave" Click="btnSave_Click" Content="Save" ></Button>
</StackPanel>
</Grid>
这为表单添加了验证,但如果我想检查模型是否有效,我该如何检查?请帮助我,因为我没有得到我在ModelState.IsValid的MVC模式中使用的IsValid属性。请帮助。
您可以使用TextBox的lostfocus事件,例如您想要对texbox 进行电子邮件验证
您的XAML
<TextBox x:Name="txtEmail1" Grid.Column="1" Grid.Row="7" MaxLength="70" Margin="0,5,5,0" Style="{StaticResource md-3s-textbox}" HorizontalAlignment="Left" LostFocus="TxtEmail1_LostFocus" >
背后的代码
public static bool IsValidEmail( string email)
{
string pattern = @"^(?!'.)(""([^""'r'']|''[""'r''])*""|" + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!'.)'.)*)(?<!'.)" + @"@[a-z0-9]['w'.-]*[a-z0-9]'.[a-z][a-z'.]*[a-z]$";
var regex = new Regex(pattern, RegexOptions.IgnoreCase);
return regex.IsMatch(email);
}
private void TxtEmail1_LostFocus(object sender, RoutedEventArgs e)
{
if (IsValidEmail(txtEmail1.Text.ToString().Trim())==false)
{
txtEmail1.ToolTip = "Invalid Email";
txtEmail1.BorderBrush= System.Windows.Media.Brushes.Red;
}
}