WPF 数据规则验证

前台代码:

<Window x:Class="WpfTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfTest"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <ControlTemplate x:Key="ErrorTemplate">
            <DockPanel LastChildFill="true">
                <Border Background="Red" DockPanel.Dock="Right" Margin="5,0,0,0" Width="20" Height="20" CornerRadius="10"
                            ToolTip="{Binding ElementName=customAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
                    <TextBlock Text="!" VerticalAlignment="center" HorizontalAlignment="center" FontWeight="Bold" Foreground="white"/>
                </Border>
                <AdornedElementPlaceholder Name="customAdorner" VerticalAlignment="Center" >
                    <Border BorderBrush="red" BorderThickness="1" />
                </AdornedElementPlaceholder>
            </DockPanel>
        </ControlTemplate>
        <Style TargetType="TextBox">
            <Setter Property="Validation.ErrorTemplate" Value="{StaticResource ErrorTemplate}" />
            <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>
    </Window.Resources>
    <Grid>
        <StackPanel Width="200">
            <TextBlock Text="姓名"/>
            <TextBox>
                <TextBox.Text>
                    <Binding Path="Name" UpdateSourceTrigger="PropertyChanged" ValidatesOnDataErrors="True">
                        <Binding.ValidationRules>
                            <local:RequiredRule/>
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox.Text>
            </TextBox>
            <TextBlock Text="年龄"/>
            <TextBox >
                <TextBox.Text>
                    <Binding Path="Age" UpdateSourceTrigger="PropertyChanged" ValidatesOnDataErrors="True">
                        <Binding.ValidationRules>
                            <local:AgeRangeRule Min="0" Max="150"/>
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox.Text>
            </TextBox>
        </StackPanel>
    </Grid>
</Window>

后台代码:

public class RequiredRule : ValidationRule
    {
        public override ValidationResult Validate(object value , System.Globalization.CultureInfo cultureInfo)
        {
            if (value == null)
                return new ValidationResult(false , "不能为空值!");
            if (string.IsNullOrEmpty(value.ToString( )))
                return new ValidationResult(false , "不能为空字符串!");

            return new ValidationResult(true , null);
        }
    }

    public class AgeRangeRule : ValidationRule
    {
        private int _min;
        private int _max;

        public AgeRangeRule( )
        {
        }

        public int Min
        {
            get { return _min; }
            set { _min = value; }
        }

        public int Max
        {
            get { return _max; }
            set { _max = value; }
        }

        public override ValidationResult Validate(object value , System.Globalization.CultureInfo cultureInfo)
        {
            int age = 0;

            try
            {
                if (((string)value).Length > 0)
                {
                    age = Int32.Parse((String)value);
                }
                else
                {
                    return new ValidationResult(false , "Illegal characters");
                }
            }
            catch (Exception e)
            {
                return new ValidationResult(false , "Illegal characters or " + e.Message);
            }

            if ((age < Min) || (age > Max))
            {
                return new ValidationResult(false ,
                  "Please enter an age in the range: " + Min + " - " + Max + ".");
            }
            else
            {
                return new ValidationResult(true , null);
            }
        }
    }

    public class RangeValidationRule :ValidationRule
    {

        public override ValidationResult Validate(object value , System.Globalization.CultureInfo cultureInfo)
        {
            double d = 0;
            if (double.TryParse(value.ToString( ) , out d))
            {
                if ((0 <= d) && (d <= 100))
                {
                    return new ValidationResult(true , null);
                }
            }

            return new ValidationResult(false , "输入值非法");
        }
    }
原文地址:https://www.cnblogs.com/hualuo-code/p/5165469.html