WPF输入框验证

WPF使用ValidationRule进行数据绑定验证

1.xaml代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<Window x:Class="WpfApp1.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:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Slider VerticalAlignment="Bottom" Minimum="0" Maximum="1000" Name="slider" Value="10"></Slider>
        <TextBox Height="50"  Name="tex" Validation.Error="tbx1_Error">
            <TextBox.Text>
                <Binding ElementName="slider" Path="Value" UpdateSourceTrigger="PropertyChanged" NotifyOnValidationError="True">
                    <Binding.ValidationRules>
                        <local:CustomValidationRule ValidatesOnTargetUpdated="True"/>
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>
        <Popup
               AllowsTransparency="True"
               PopupAnimation="Slide"
               PlacementTarget="{Binding ElementName=tex}"
               Placement="Bottom"
               Width="{Binding ElementName=tex, Path=ActualWidth}"
               IsOpen="{Binding RelativeSource={RelativeSource AncestorType=Window,AncestorLevel=1},Path=PopupIsOpen,Mode=OneWay}">
            <Label FontSize="15" Height="50" Content="{Binding  RelativeSource={RelativeSource AncestorType=Window,AncestorLevel=1},Path=TipMessage}" Foreground="Red">
 
            </Label>
        </Popup>
    </Grid>
</Window>

  2、后台代码如下:

复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
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.Navigation;
using System.Windows.Shapes;

namespace WpfApp1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        private string inputText;
        public string InputText
        {
            get { return inputText; }
            set
            {
                inputText = value;
                OnPropertyChanged(nameof(InputText));
            }
        }
        private string TipMessage_;

        public string TipMessage
        {
            get { return TipMessage_; }
            set { TipMessage_ = value;
                OnPropertyChanged(nameof(TipMessage));
            }
        }

        private bool PopupIsOpen_;

        public bool PopupIsOpen
        {
            get { return PopupIsOpen_;
            }
            set { PopupIsOpen_ = value;
                OnPropertyChanged(nameof(PopupIsOpen));
            }
        }

        public MainWindow()
        {
            InitializeComponent();
        }
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //if (Validation.GetHasError(txtInput))
            //{
            //    MessageBox.Show("输入验证未通过!");
            //}
            //else
            //{
            //    MessageBox.Show("输入验证通过!");
            //}
        }
        private void tbx1_Error(object sender, ValidationErrorEventArgs e)
        {
            if (Validation.GetErrors(tex).Count > 0)
            {
                PopupIsOpen = true;
                TipMessage = Validation.GetErrors(tex)[0].ErrorContent.ToString();
            }
            else
            {
                PopupIsOpen = false;
                TipMessage = "";
            }
        }
    }
}
复制代码

3、新建一个class代码如下:

复制代码
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;

namespace WpfApp1
{
    public class CustomValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            double myValue = 0;
            if (double.TryParse(value.ToString(), out myValue))
            {
                if (myValue >= 0 && myValue <= 100)
                {
                    return new ValidationResult(true, null);
                }
            }
            return new ValidationResult(false, "输入的数字必须在0到100之间");
        }
    }
}
复制代码

最后看效果

 

posted @   ¥东方不败  阅读(28)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示