【问题标题】:how do i apply Validation Attributes to WPF我如何将验证属性应用于 WPF
【发布时间】:2012-05-23 17:46:56
【问题描述】:

在我的项目中,我有这个窗口可以添加新的Contact 对象

我的问题是我如何像在 Asp.net MVC 中那样将此验证属性应用于 WPF 窗口.. 像 [Required] 和一些 [ReularExpression()]

<Window x:Class="WPFClient.AddNewContact"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="AddNewContact" Height="401" Width="496" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:my="clr-namespace:WPFClient.PhoneBookServiceReference" Loaded="Window_Loaded">
    <Window.Resources>
    </Window.Resources>
    <Grid Height="355" Width="474">
        <GroupBox Header="Add Contact" Margin="0,0,0,49">
            <Grid HorizontalAlignment="Left" Margin="21,21,0,0" Name="grid1" VerticalAlignment="Top" Height="198" Width="365">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition Width="194" />
                    <ColumnDefinition Width="64*" />
                </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="53" />
                    <RowDefinition Height="17*" />
                </Grid.RowDefinitions>

                <Label Content="Name:" Grid.Column="0" Grid.Row="0" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
                <TextBox Grid.Column="1" Grid.Row="0" Height="23" HorizontalAlignment="Left" Margin="0,3,0,6" Name="nameTextBox" VerticalAlignment="Center" Width="120" />

                <Label Content="Email:" Grid.Column="0" Grid.Row="1" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
                <TextBox Grid.Column="1" Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="0,3,0,6" Name="emailTextBox" VerticalAlignment="Center" Width="120" />

                <Label Content="Phone Number:" Grid.Column="0" Grid.Row="2" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
                <TextBox Grid.Column="1" Grid.Row="2" Height="23" HorizontalAlignment="Left" Margin="0,3,0,6" Name="phoneNumberTextBox" VerticalAlignment="Center" Width="120" />

                <Label Content="Mobil:" Grid.Column="0" Grid.Row="3" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
                <TextBox Grid.Column="1" Grid.Row="3" Height="23" HorizontalAlignment="Left" Margin="0,3,0,6" Name="mobilTextBox" VerticalAlignment="Center" Width="120" />


                <Label Content="Address:" Grid.Column="0" Grid.Row="4" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
                <TextBox  Grid.Row="4" Grid.Column="1" Height="39" HorizontalAlignment="Left" Margin="0,0,0,14" Name="addressTextBox" 
                             VerticalAlignment="Center" Width="194" TextWrapping="Wrap" VerticalScrollBarVisibility="Visible" AcceptsReturn="True"  />
            </Grid>
        </GroupBox>
             <Button Content="Add" Height="23" HorizontalAlignment="Left" Margin="24,273,0,0" Name="btnAdd" VerticalAlignment="Top" Width="75" Click="btnAdd_Click" />
        <Button Content="Cancel" Height="23" HorizontalAlignment="Left" Margin="123,273,0,0" Name="btnCancel" VerticalAlignment="Top" Width="75" Click="btnCancel_Click" />

    </Grid>
</Window>

我有这个 ModelView 类来映射联系人对象

 public class MContact
 {
      [Required(ErrorMessage = " Name is required.")]
      [StringLength(50, ErrorMessage = "No more than 50 characters")]
      [Display(Name = "Name")]
      public string Name { get; set; }


      [Required(ErrorMessage = "Email is required.")]
      [StringLength(50, ErrorMessage = "No more than 50 characters")]
      [RegularExpression(".+\\@.+\\..+", ErrorMessage = "Valid email required e.g. abc@xyz.com")]
      public string Email { get; set; }


      [Display(Name = "Phone Number")]
      [Required]
      [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$",
            ErrorMessage = "Entered phone format is not valid.")]
      public string PhoneNumber { get; set; }

      public string Address { get; set; }
      [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$",
    ErrorMessage = "Entered phone format is not valid.")]
      public string Mobil { get; set; }

 }

【问题讨论】:

    标签: c# wpf validation viewmodel data-annotations


    【解决方案1】:
    1. 创建ValidatorBase

      它实现了标准的 .net IDataErrorInfo。 它适用于 WPF,但也适用于 Windows 窗体

    public abstract class ValidatorBase : IDataErrorInfo
    {
      string IDataErrorInfo.Error
      {
        get
        {
          throw new NotSupportedException("IDataErrorInfo.Error is not supported, use IDataErrorInfo.this[propertyName] instead.");
        }
      }
      string IDataErrorInfo.this[string propertyName]
      {
        get
        {
          if (string.IsNullOrEmpty(propertyName))
          {
            throw new ArgumentException("Invalid property name", propertyName);
          }
          string error = string.Empty;
          var value = GetValue(propertyName);
          var results = new List<System.ComponentModel.DataAnnotations.ValidationResult>(1);
          var result = Validator.TryValidateProperty(
              value,
              new ValidationContext(this, null, null)
              {
                MemberName = propertyName
              },
              results);
          if (!result)
          {
            var validationResult = results.First();
            error = validationResult.ErrorMessage;
          }
          return error;
        }
      }
      private object GetValue(string propertyName)
      {
        PropertyInfo propInfo = GetType().GetProperty(propertyName);
        return propInfo.GetValue(this);
      }
    }
    
    1. 联系 ValidatorBase 的继承
    public class MContact : ValidatorBase
    {
        [Required(ErrorMessage = " Name is required.")]
        [StringLength(50, ErrorMessage = "No more than 50 characters")]
        [Display(Name = "Name")]
        public string Name { get; set; }
    
    1. 不要忘记在要验证的控件上放置一些验证触发器
    <TextBox Text="{Binding Path=Address,
                            UpdateSourceTrigger=PropertyChanged,                 
                            ValidatesOnDataErrors=True}" />
    
    1. 添加一些样式以在所有文本框上显示错误工具提示
    <Window.Resources>
        <Style TargetType="{x:Type TextBox}">
            <Setter Property="ToolTip">
                <Setter.Value>
                    <Binding RelativeSource="{RelativeSource Self}" Path="(Validation.Errors)[0].ErrorContent" />
                </Setter.Value>
            </Setter>
            <Setter Property="Margin" Value="4,4" />
        </Style>
    </Window.Resources>
    

    代码在 Github 上:

    https://github.com/EmmanuelDURIN/wpf-attribute-validation

    灵感来自:

    https://code.msdn.microsoft.com/windowsdesktop/Validation-in-MVVM-using-12dafef3

    实施愉快:-)

    【讨论】:

    • @Vimes,我正确回答了这个问题。我建议的 ViewModel 类或继承 ValidatorBase 类的业务类使 StringLengthAttribute 和其他类……适用于 ViewModel 对象的属性。我正确回答了“如何将验证属性应用于 wpf?”这个问题。转到 GitHub 示例,其中 Contact 类继承了 ValidatorBase。我用他的 MContact 课程严格回答了 Tarek Saied 的例子。我不同意投反对票
    • 伊曼纽尔,对不起,你是对的。答案没有直接显示属性用法,所以我错误地认为它是 IDataErrorInfo 操作方法。我对其进行了编辑以显示属性用法并进行了投票。现在应该好了:)
    【解决方案2】:

    如果你想走这条路,我建议你看看下面的文章。一切以IDataErrorInfo为中心。

    MSDN: How to: Implement Validation Logic on Custom Objects

    CodeProject: Attributes-based Validation in a WPF MVVM

    【讨论】:

    • 仅供参考,MSDN 文章的链接有changed
    【解决方案3】:

    从 WPF 4.5 开始,您可以在模型上实现 INotifyDataErrorInfo,WPF 控件将绑定到验证消息。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    相关资源
    最近更新 更多