WPF MVVM数据提交验证正确性

8 篇文章 1 订阅
4 篇文章 0 订阅

点击保存时,验证数据是否正确。

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>

demo下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值