zl程序教程

您现在的位置是:首页 >  后端

当前栏目

wpf ValidationRule数据验证

WPF数据 验证
2023-09-14 09:16:30 时间

先写验证规则代码

 public class RangeValidationRule  : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            Double D = 0;
            if (double.TryParse(value.ToString(), out D))
            {
                if (D > 0 && D < 100) 
                {
                    return new ValidationResult(true,null);//验证成功
                }
            }
            return new ValidationResult(false, "Validation Failed");//验证失败
        }

    }

xaml界面

<Window x:Class="WpfApp1.Window8"
        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:WpfApp1"
        xmlns:Validatarolus="clr-namespace:WpfApp1.ValidationRules"
        mc:Ignorable="d"
        Title="Window8" Height="450" Width="800">
    <Grid x:Name="grid">
        <StackPanel>
            <Slider x:Name="slider" Maximum="1000"></Slider>

            
            <TextBox Validation.Error="TextBox_Error">
                <TextBox.Text>
                    <Binding ElementName="slider" Path="Value" UpdateSourceTrigger="PropertyChanged" NotifyOnValidationError="True">
                        <Binding.ValidationRules>
                            <Validatarolus:RangeValidationRule ValidatesOnTargetUpdated="True"></Validatarolus:RangeValidationRule>
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox.Text>
            </TextBox>
            <Button Content="提交" Click="Button_Click"></Button>
        </StackPanel>
    </Grid>
</Window>
public partial class Window8 : Window
    {
        public Window8()
        {
            InitializeComponent();
        }

        private void TextBox_Error(object sender, ValidationErrorEventArgs e)
        {
           
            if (Validation.GetErrors(sender as FrameworkElement).Count > 0)
            {
                (sender as FrameworkElement).ToolTip =Validation.GetErrors(sender as FrameworkElement)[0].ErrorContent.ToString();
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string message;
            if (HasErrors(out message))
            {
                MessageBox.Show(message);
            }
        }
        private bool HasErrors(out string message)
        {
            StringBuilder sb = new StringBuilder();
            GetError(sb, this.grid);
            message = sb.ToString();
            return !string.IsNullOrWhiteSpace(message);
        }
        private void GetError(StringBuilder sb, DependencyObject obj)
        {
            foreach (object child in LogicalTreeHelper.GetChildren(obj))
            {
                StackPanel element = child as StackPanel;
                if (element == null) continue;

                foreach (var ele in element.Children)
                {
                    TextBox textBox = ele as TextBox;
                    if (textBox == null) continue;
                    if (Validation.GetHasError(textBox))
                    {
                        foreach (ValidationError error in Validation.GetErrors(textBox))
                        {
                            sb.Append(error.ErrorContent.ToString() + "\r\n");
                        }
                        GetError(sb, element);
                    }

                }
            }
        }

    }