MVVM的数据验证

对于增删改查的软件而言,前端验证放在统一的地方验证,不要做重复的工作,不需要每个页面都添加非空验证和其他类似的验证

1  使用默认的错误模板提示

效果

 a、  先创建一个非空的规则,继承ValidationRule

/// <summary>
/// 非空规则
/// </summary>
public class C_NotEmptyRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (value is string str && string.IsNullOrWhiteSpace(str))
{
return new ValidationResult(false, "不能为空.");
}
return ValidationResult.ValidResult;
}
}

 

b、 页面调用

添加命名空间  

       xmlns:dataserver="clr-namespace:MachineVision.Core.Sevices"

            <TextBlock  Text="非空验证:"  Margin="20"/>
            <TextBox x:Name="txt2">
                <TextBox.Text>
                    <Binding Path="Name" UpdateSourceTrigger="PropertyChanged" >
                        <Binding.ValidationRules>
                            <dataserver:C_NotEmptyRule />
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox.Text>
            </TextBox>

2  清楚默认的错误模板提示,使用自定义的提示

 a、  添加一个范围限制规则

    /// <summary>
    /// 数值范围规则
    /// </summary>
    public class C_RangeRule : ValidationRule
    {
        public int MaxVal { get; set; }
        public int MinVal { get; set; }
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            
          if (value!=null)
          {
                string str = value.ToString();
                 int.TryParse(str,out int age);
                if (age >= MinVal && age <= MaxVal)
                {
                    return ValidationResult.ValidResult;
                }
                else
                {
                    return new ValidationResult(false, $" must be between {MinVal} and {MaxVal}.");
                }
            }
            else
            {
                return new ValidationResult(false, "Invalid data type.");
            }
        }
    }

b 、 页面调用

       <TextBlock  Text="限制在 18-100之间年纪: 去除原生的提示 " />
            <TextBox x:Name="txt1"  Margin="20">
                <TextBox.Text>
                    <Binding Path="Age" UpdateSourceTrigger="PropertyChanged">
                        <Binding.ValidationRules>
                            <dataserver:C_RangeRule MinVal="5"  MaxVal="100"  />
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox.Text>
                <TextBox.Style>
                    <Style TargetType="{x:Type TextBox}">
                        <Style.Setters>
                            <Setter Property="Validation.ErrorTemplate">
                                <Setter.Value>
                                    <ControlTemplate/>
                                </Setter.Value>
                            </Setter>
                        </Style.Setters>
                    </Style>
                </TextBox.Style>
            </TextBox>


            <Popup 
                IsOpen="{Binding ElementName=txt1,Mode=OneWay,Path=(Validation.HasError)}"
                AllowsTransparency="True"  PopupAnimation="Scroll" Placement="Bottom"
                PlacementTarget="{Binding ElementName=txt1}">
                <Border Background="Red"  Height="30">
                    <TextBlock  FontSize="25" Text="{Binding ElementName=txt1,Path=(Validation.Errors)[0].ErrorContent}">
                    </TextBlock>
                </Border>
            </Popup>

 

3  多个规则混合使用

            <TextBlock  Text="混合验证 非空,18-100之间: :"  Margin="20"/>
            <TextBox x:Name="txt3">
                <TextBox.Text>
                    <Binding Path="Total" UpdateSourceTrigger="PropertyChanged" >
                        <Binding.ValidationRules>
                            <dataserver:C_NotEmptyRule />
                            <dataserver:C_RangeRule MinVal="5"  MaxVal="100"  />
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox.Text>
            </TextBox>

 

posted @ 2024-08-08 10:06  陌念  阅读(14)  评论(0)    收藏  举报