WPF 数据验证 ValidationRule

样式通上一篇:https://www.cnblogs.com/huvjie/p/16867618.html

xaml:

<Window x:Class="MyWPFSimple1.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:MyWPFSimple1"
        mc:Ignorable="d"
        Title="MainWindow" Height="100" Width="450">
    <Window.DataContext>
        <local:MainVM/>
    </Window.DataContext>
    <Grid>
        <StackPanel Orientation="Horizontal" Margin="10">
            <TextBlock Text="测试信息" Width="100" VerticalAlignment="Center"/>
            <TextBox Width="150" VerticalAlignment="Center" BorderBrush="Black">
                <TextBox.Text>
                    <Binding Path="MyTest" UpdateSourceTrigger="PropertyChanged">
                        <Binding.ValidationRules>
                            <local:RequiredRule />
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox.Text>

            </TextBox>
        </StackPanel>
    </Grid>
</Window>

viewModel:

public class MainVM : ObservableObject
{
    private string m_MyTest;

    public string MyTest
    {
        get { return m_MyTest; }
        set { m_MyTest = value;  RaisePropertyChanged(nameof(MyTest)); }
    }
}

ValidationRule:

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




参考:
https://www.cnblogs.com/wzh2010/p/6518834.html

posted @   double64  阅读(172)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示