WPF 数据验证

时间:2021-07-29
本文章向大家介绍WPF 数据验证,主要包括WPF 数据验证使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

参照了官网,但是 Error样式还是花了不少时间

<Window x:Class="WpfDemo.BindingValidationDemo2"
        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:WpfDemo"
        mc:Ignorable="d"
        Title="BindingValidationDemo2" Height="300" Width="300"
        >
    <Window.Resources>
        <ControlTemplate x:Key="validationTemplate">
            <DockPanel>
                <TextBlock Foreground="Red" FontSize="20">!</TextBlock>
                <AdornedElementPlaceholder/>
            </DockPanel>
        </ControlTemplate>
        <Style x:Key="textBoxInError" TargetType="{x:Type TextBox}">
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">
                    <Setter Property="ToolTip"
        Value="{Binding RelativeSource={x:Static RelativeSource.Self},
                        Path=(Validation.Errors)/ErrorContent}"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <Grid>
        <TextBox Name="textBox1" FontSize="15"
         Validation.ErrorTemplate="{StaticResource validationTemplate}"
         Style="{StaticResource textBoxInError}" Margin="68,31,72,198">
            <TextBox.Text>
                <Binding Path="Text" RelativeSource="{RelativeSource Self}"
               NotifyOnValidationError="True" NotifyOnTargetUpdated="True">
                    <Binding.ValidationRules>
                        <local:AgeRangeRule Min="21" Max="130" ValidatesOnTargetUpdated="True"/>
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>
        <!--<Slider Maximum="100" Minimum="0" IsSnapToTickEnabled="True" x:Name="slider" HorizontalAlignment="Left" Margin="68,101,0,0" VerticalAlignment="Top" Width="150"/>-->
    </Grid>
</Window>

  

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfDemo
{
    /// <summary>
    /// RelativeSourceDemo2.xaml 的互動邏輯
    /// </summary>
    public partial class BindingValidationDemo2 : Window
    {
        public BindingValidationDemo2()
        {
            InitializeComponent();
        }
    }
    class AgeRangeRule : ValidationRule
    {
        public int Min { get; set; }
        public int Max { get; set; }

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

            try
            {
                if (((string)value).Length > 0)
                    age = Int32.Parse((String)value);
            }
            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}.");
            }
            return ValidationResult.ValidResult;
        }
    }
}

  

原文地址:https://www.cnblogs.com/JerryZhang320/p/15076950.html