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);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了