WPF 数据验证 丰富样式 前端设定

 

 

<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"
        Title="BindingValidationDemo2" Height="300" Width="300"
        >
    <Window.Resources>
        <ControlTemplate x:Key="validationTemplate">
            <DockPanel>
                <!--<TextBlock Foreground="Red" FontSize="20">!</TextBlock>
                <AdornedElementPlaceholder/>-->
                <TextBlock DockPanel.Dock="Bottom" Foreground="Red" FontSize="13"  
                                Text="{Binding ElementName=errorHint, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
                </TextBlock>
                <TextBlock Foreground="Red" FontSize="20" DockPanel.Dock="Top">-----------!</TextBlock>
                <TextBlock Foreground="Red" FontSize="20">!</TextBlock>
                <Border BorderBrush="Red" BorderThickness="1">
                    <AdornedElementPlaceholder Name="errorHint" />
                    <!--AdornedElementPlaceholder元素的支持,该元素是一个占位符,
                    跟被验证控件有着同样的位置和尺寸;而且还可以通过此类的AdornedElement属性来访问被验证控件。-->
                </Border>
                <TextBlock Foreground="Red" FontSize="20">!!</TextBlock>
            </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;
        }
    }
}

  

posted @ 2021-07-31 13:43  zq爱生活爱代码  阅读(72)  评论(0编辑  收藏  举报