WPF 绑定数据有效性检查

(1) 列表控件绑定数据对象集合

<ListBox Name="lstProducts" Margin="5" DisplayMemberPath="ModelName"/>

(2) Grid控件绑定到列表元素,指定为选中的对象,并做错误检查

<Grid Name="gridProductDetails" DataContext="{Binding ElementName=lstProducts, Path=SelectedItem}" Validation.Error="validationError">

设置Grid的资源:

<Grid.Resources>
      <Style TargetType="{x:Type TextBox}">
            <Setter Property="Validation.ErrorTemplate">
                  <Setter.Value>
                      <ControlTemplate>
                          <DockPanel LastChildFill="True">
                              <TextBlock DockPanel.Dock="Right" Foreground="Red" FontSize="14" FontWeight="Bold" ToolTip="{Binding ElementName=adornerPlaceholder,  Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">*</TextBlock>

                    <Border BorderBrush="Green" BorderThickness="1">
                          <AdornedElementPlaceholder Name="adornerPlaceholder"></AdornedElementPlaceholder>
                      </Border>
                  </DockPanel>
        </ControlTemplate>
    </Setter.Value>
</Setter>

<Style.Triggers>
        <Trigger Property="Validation.HasError" Value="true">
              <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},Path=(Validation.Errors)[0].ErrorContent}"/>
        </Trigger>
</Style.Triggers>
</Style>
</Grid.Resources>

(3) 在Grid中的文本控件绑定对象的属性值,做数据有效性的检查

<TextBox Margin="5" Grid.Column="1">
      <TextBox.Text>
            <Binding Path="ModelNumber" NotifyOnValidationError="true">
              <Binding.ValidationRules>
                    <DataErrorValidationRule></DataErrorValidationRule>
                </Binding.ValidationRules>
            </Binding>
      </TextBox.Text>
  </TextBox>
<TextBox Margin="5" Grid.Row="2" Grid.Column="1">
      <TextBox.Text>
          <Binding Path="UnitCost" NotifyOnValidationError="true" StringFormat="{}{0:C}">
              <Binding.ValidationRules>
                  <local:PositivePriceRule Max="999.99"></local:PositivePriceRule>
                                <ExceptionValidationRule></ExceptionValidationRule>
                </Binding.ValidationRules>
            </Binding>
    </TextBox.Text>
</TextBox>

(4)检查类

using System.Windows.Controls;
using System.Globalization;

namespace WpfApp
{
    public class PositivePriceRule : ValidationRule
    {
        private decimal min = 0;
        private decimal max = Decimal.MaxValue;
        public decimal Min
        {
            get { return min; }
            set { min = value; }
        }

        public decimal Max
        {
            get { return max; }
            set { max = value; }
        }

        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            decimal price = 0;
            try
            {
                if (((string)value).Length > 0)
                    //Allow number styles with currency symbols like $
                    price = decimal.Parse((string)value, System.Globalization.NumberStyles.Any);
            }
            catch (Exception e)
            {
                return new ValidationResult(false, "Illegal characters");
            }
            if ((price < min) || (price > Max))
            {
                return new ValidationResult(false, "NOT in the reange " + Min + " to " + Max);
            }
            else
            {
                return new ValidationResult(true, null);
            }

        }
    }

}

  

效果如下:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

flysh05

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

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

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

打赏作者

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

抵扣说明:

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

余额充值