WPF中数据绑定验证深入讲解

WPF中数据绑定验证深入讲解

WPF在用户输入时,提供了验证功能,通常验证使用以下两种方式来实现:

  1. 在数据对象中引发错误。通常是在属性设置过程中抛出异常,或者在数据类中实现INotifyDataErrorInfoIDataErrorInfo接口。
  2. 在绑定级别定义验证。

只有来自目标的值正在被用于更新数据源时才会应用验证。

数据对象中设置验证

  1. 在属性中Set上抛出异常
public class MyData
{
    private string _value = "200";

    public string Value
    {
        get { return _value; }
        set
        {
            _value = value;

            if (value == "123")
                throw new System.Exception("报错了~~~[Exception]");
        }
    }
}
  1. 直接抛出异常,wpf经常会忽略,从而得不到异常的信息,此时需要借助ExceptionValidationRule

ExceptionValidationRule是预先构建的验证规则,它向WPF发出所有的异常报告。它必须在<Binding.ValidationRules>里面

<TextBox x:Name="tb1">
    <TextBox.Text>
        <Binding Path="Value" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <ExceptionValidationRule />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

ExceptionValidationRule在绑定过程中发生的所有异常,包括编辑的值不能转为正确类型、属性设置器异常以及值转换器异常(float转为string)。当出现验证失败后,System.Windows.Controls.Validation类的附加属性会记录下错误:

  • 在绑定元素上,Validation.HasError为True,同时会自动将控件的模板切换为Validation.ErrorTemplate定义的模板。
  • ValidationRule.Validate()会返回ValidationError,其中中包含错误细节
  • 如果Binding.NotifyOnValidationError被设置为True,则会在绑定元素上引发Validation.Error事件

INotifyDataErrorInfo

INotifyDataErrorInfoINotifyDataErrorInfo都有类似作用,但是INotifyDataErrorInfo界面更加丰富。与上面不同的是,实现INotifyDataErrorInfoIDataErrorInfo接口时,允许用户修改为非法值,只不过给出错误提示。

image-20231108111152474

使用INotifyDataErrorInfo的案例

  1. 新建一个Data类
//类实现了INotifyDataErrorInfo接口,该接口定义了HasErrors属性和GetErrors方法,以及ErrorsChanged事件
public class Data : INotifyDataErrorInfo,INotifyPropertyChanged
{
    //key为属性名,value为错误信息列表
    Dictionary<string, List<string>> errors = new();

    void SetErrors(string propertyName, List<string> value)
    {
        errors.Remove(propertyName);
        errors.Add(propertyName, value);
        if (ErrorsChanged != null)
        {
            ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
        }
    }
    void ClearErrors(string propertyName)
    {
        errors.Remove(propertyName);
        if (ErrorsChanged != null)
        {
            ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
        }
    }
    public bool HasErrors => errors.Count>0;

    public event EventHandler<DataErrorsChangedEventArgs>? ErrorsChanged;
    public event PropertyChangedEventHandler? PropertyChanged;

    public IEnumerable Errors => GetErrors("ModelNumber");
    public IEnumerable GetErrors(string? propertyName)
    {
        if (propertyName is null or { Length: <= 0 })
        {
            return errors.Values;
        }
        else
        {
            if (errors.ContainsKey(propertyName))
            {
                return errors[propertyName];
            }
            else
            {
                return null;
            }
        }
    }

    private string modelNumber;

    public string ModelNumber
    {
        get { return modelNumber; }
        set { modelNumber = value;
            bool valid = true;
            foreach (char c in modelNumber)
            {
                if (!char.IsLetterOrDigit(c))
                {
                    valid = false;  
                    break;
                }
            }
            if (!valid)
            {
                List<string> errors = new(); 
                errors.Add("ModelNumber不能含有标点符号,空格等");
                SetErrors("ModelNumber", errors);
            }
            else
            {
                ClearErrors("ModelNumber");
            }
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("ModelNumber"));
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("HasErrors"));
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Errors"));
        }
    }
}
  1. 做一个界面,绑定ModelNumber
<Window ...>
    <Window.DataContext>
        <local:Data/>
    </Window.DataContext>
    <StackPanel>
        <TextBox Text="{Binding ModelNumber ,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True}"/>
        <TextBlock>
            <Run Text="是否有错误"/>
            <Run Text="{Binding HasErrors, Mode=OneWay}"/>
        </TextBlock>
        <ListView ItemsSource="{Binding Errors}"/>
    </StackPanel>
</Window>

动图

自定义验证规则

自定义验证规则很像自定义转换器

  1. 针对某个属性自定义验证规则
public class ValueRule : ValidationRule
{

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        if (value?.ToString() == "123") return new ValidationResult(false, "输入的值不在范围内");
        return new ValidationResult(true, null);
    }
}
  1. 界面上使用验证规则
<StackPanel>
    <TextBox>
        <TextBox.Text>
            <Binding Path="Max" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay">
                <Binding.ValidationRules>
                    <local:ValueRule/>
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>
</StackPanel>

可以看出,<Binding.ValidationRules>下面可以放置多个验证规则,按顺序执行,当所有的验证规则都通过后,则调用转换器(如果存在),其中ExceptionValidationRule比较特殊,当输入内容不能转换为其他规则所定义的转换时,也会触发。

错误显示

首先只有设置了Binding.NotifyOnValidationError为true时,才会引发Validation.Error事件,当含有错误时,可以使用静态类Validation中的附加属性ErrorsHasError来获取信息。

通常出现错误时,边框显示未红色,也可以自行设置错误模板,错误模板位于装饰层,它位于普通窗口内容之上。

<TextBox Width="130">
    <TextBox.Text>
        <Binding
            Mode="TwoWay"
            Path="Max"
            UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <local:ValueRule />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
    <Validation.ErrorTemplate>
        <ControlTemplate>
            <DockPanel LastChildFill="True">
                <TextBlock
                    DockPanel.Dock="Right"
                    Foreground="Red"
                    Text="*" />
                <Border BorderBrush="Green" BorderThickness="2">
                    <AdornedElementPlaceholder />
                </Border>
            </DockPanel>
        </ControlTemplate>
    </Validation.ErrorTemplate>
</TextBox>

image-20231108140348940

其中AdornedElementPlaceholder代表控件本身,上面案例中是将*放入了控件周围,如果想将*重叠放到控件上面,可以使用Grid,放在同一窗格。

<Validation.ErrorTemplate>
    <ControlTemplate>
        <Grid>
            <TextBlock
                Margin="50,5,0,0"
                DockPanel.Dock="Right"
                Foreground="Red"
                Text="*" />
            <Border BorderBrush="Green" BorderThickness="2">
                <AdornedElementPlaceholder />
            </Border>
        </Grid>
    </ControlTemplate>
</Validation.ErrorTemplate>

image-20231108141002670

但是这样显示不出错误信息,可以使用ToolTip来显示第一个错误内容

<Validation.ErrorTemplate>
    <ControlTemplate>
        <Grid>
            <TextBlock
                Margin="50,5,0,0"
                DockPanel.Dock="Right"
                Foreground="Red"
                Text="*"
                ToolTip="{Binding ElementName=adornerPlaceholder, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}" />
            <Border BorderBrush="Green" BorderThickness="2">
                <AdornedElementPlaceholder x:Name="adornerPlaceholder" />
            </Border>
        </Grid>
    </ControlTemplate>
</Validation.ErrorTemplate>

上面模板中使用了AdornedElementPlaceholderAdornedElement属性指向背后的元素。

动图

这样只有悬浮在后面的*号时才会显示错误信息,如果想作为TextBox元素本身的ToolTip,可借助Validation.HasError可以实现。

<TextBox Width="130">
    <TextBox.Text>
        <Binding
            Mode="TwoWay"
            Path="Max"
            UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <local:ValueRule />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
    <Validation.ErrorTemplate>
        <ControlTemplate>
            <Grid>
                <TextBlock
                    Margin="50,5,0,0"
                    DockPanel.Dock="Right"
                    Foreground="Red"
                    Text="*"
                    ToolTip="{Binding ElementName=adornerPlaceholder, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}" />
                <Border BorderBrush="Green" BorderThickness="2">
                    <AdornedElementPlaceholder x:Name="adornerPlaceholder" />
                </Border>
            </Grid>
        </ControlTemplate>
    </Validation.ErrorTemplate>
    <TextBox.Style>
        <Style TargetType="TextBox">
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="True">
                    <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Mode=Self}, Path=(Validation.Errors)[0].ErrorContent}" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>

动图

验证多个值

很多时候需要动态验证多个绑定值,比如有两个属性,一个Max,一个Min,要求是用户输入Min必须小于Max,要实现这个功能可以使用绑定组来创建。

绑定组的原理很简单,同样是创建继承自ValidationRule的类,不同的是,不能将该规则绑定到单个绑定表达式,而是将其附加到包含所有绑定控件的容器上。

  1. ViewModel中有两个属性
public class Data : INotifyDataErrorInfo,INotifyPropertyChanged
{
    public int Max { set; get; } = 100;
    public int Min { set; get; } = 1;
}
  1. 创建验证规则
public class ValueRule : ValidationRule
{
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        BindingGroup bindingGroup = (BindingGroup)value;
        var d= (Data)bindingGroup.Items[0];
        if (d.Min >= d.Max)
        {
            return new ValidationResult(false, "错误,最小值必须小于最大值");
        }
        return new ValidationResult(true, null);
    }
}
  1. UI上绑定,注意,此处要在Grid中添加绑定组
<Grid Margin="60" TextBox.LostFocus="Grid_LostFocus">
    <Grid.BindingGroup>
        <BindingGroup x:Name="customGroup">
            <BindingGroup.ValidationRules>
                <local:ValueRule />
            </BindingGroup.ValidationRules>
        </BindingGroup>
    </Grid.BindingGroup>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>
    <TextBox
        x:Name="ddd"
        Grid.Row="0"
        Text="{Binding Path=Max, BindingGroupName=customGroup, UpdateSourceTrigger=PropertyChanged}" />
    <TextBox Grid.Row="1" Text="{Binding Path=Min, BindingGroupName=customGroup, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
  1. 此时并不会验证,绑定组使用了事务处理编辑系统,只有正式提交后才会进行验证,所以在Grid上增加事件,当TextBox失去焦点时触发
private void Grid_LostFocus(object sender, RoutedEventArgs e)
{
    customGroup.CommitEdit();
}
  1. 如果验证失败,则整个Grid会认为是无效的。

    动图

注意:

  1. 当存在多个绑定组时,要为BindingGroup设置Name,这样可以在具体绑定时设置绑定组Text="{Binding Path=Max, BindingGroupName=customGroup, UpdateSourceTrigger=PropertyChanged}" />
  2. 默认情况时,Validate方法中接收到的数据是原始对象,而不是新修改的值,所以为了验证新值,可以使用GetValue方法
BindingGroup bindingGroup = (BindingGroup)value;
var d = (Data)bindingGroup.Items[0];
var newValue = bindingGroup.GetValue(d, "Min");
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

步、步、为营

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值