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);
    }
}
 
                    
                     
                    
                 
                    
                 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号