点击保存时,验证数据是否正确。
1.先建一个类User
public class User
{
public string Name { get; set; }
public int Age { get; set; }
}
2.建UserViewModel
public class UserViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private User _modelObject = new User();
public UserViewModel(User model)
{
if (model != null)
{
_modelObject = model;
}
}
public string Name
{
get => _modelObject.Name;
set
{
_modelObject.Name = value;
OnPropertyChanged("ID");
}
}
public int Age
{
get => _modelObject.Age;
set
{
_modelObject.Age = value;
OnPropertyChanged("Age");
}
}
}
3.建ValidationRule类
public class NotEmptyValidationRule: ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (value != null)
{
if (value.ToString() == "")
{
return new ValidationResult(false,"请输入内容");
}
return ValidationResult.ValidResult;
}
return new ValidationResult(false,"请输入内容");
}
}
public class AgeValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (value != null)
{
var flag = int.TryParse(value.ToString(), out var age);
if (!flag)
{
return new ValidationResult(false,"请输入正确的数字");
}
if (age > 120 || age < 0)
{
return new ValidationResult(false,"请输入正确的年龄");
}
return ValidationResult.ValidResult;
}
return new ValidationResult(false,"*");
}
}
4.MainWindow后台
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
}
public UserViewModel _CurrentModel;
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
if (!IsValidate(this)) //这里this是当前页面,如果页面有多个datacontent,应该传不同的datacontent
{
MessageBox.Show("数据有误,请检查页面");
return;
}
MessageBox.Show("保存成功");
}
private void Window_Load(object sender, RoutedEventArgs e)
{
_CurrentModel=new UserViewModel(new User());
this.DataContext = _CurrentModel;
}
private bool IsValidate(DependencyObject node)
{
//查找页面有错误的控件
if (node != null)
{
bool isValid = !Validation.GetHasError(node);
if (!isValid)
{
// If the dependency object is invalid, and it can receive the focus,
// set the focus
if (node is IInputElement) Keyboard.Focus((IInputElement)node);
return false;
}
foreach (object subnode in LogicalTreeHelper.GetChildren(node))
{
if (subnode is DependencyObject)
{
// If a child dependency object is invalid, return false immediately,
// otherwise keep checking
if (IsValidate((DependencyObject)subnode) == false) return false;
}
}
return true;
}
return false;
}
}
5.MainWindow前台
<Window x:Class="WpfApplication1.MainWindow"
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:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Load">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<WrapPanel Grid.Row="0">
<TextBlock Text="姓名:"></TextBlock>
<TextBox Width="100" >
<TextBox.Text>
<Binding Path="Name" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<local:NotEmptyValidationRule ValidationStep="ConvertedProposedValue" ValidatesOnTargetUpdated="True"></local:NotEmptyValidationRule>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" />
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
</WrapPanel>
<WrapPanel Grid.Row="1">
<TextBlock Text="年龄:"></TextBlock>
<TextBox Width="100" >
<Binding Path="Age" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<local:AgeValidationRule ValidationStep="ConvertedProposedValue" ValidatesOnTargetUpdated="True"></local:AgeValidationRule>
</Binding.ValidationRules>
</Binding>
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" />
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
</WrapPanel>
<WrapPanel Grid.Row="2" VerticalAlignment="Center" HorizontalAlignment="Center">
<Button Content="确定" Width="100" Click="ButtonBase_OnClick"></Button>
</WrapPanel>
</Grid>
</Window>