English 中文(简体)
如何将校验属性应用到 WPF
原标题:how do i apply Validation Attributes to WPF

在我的工程中, 我有一个窗口可以添加新的 contact 对象

我的疑问是,我如何像在Asp.net MVC中那样对 WPF 窗口应用此校验属性 。 例如 [required] 和一些 [ReturalExpression ()]

<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>

我有这个模型查看类来绘制联系人对象的地图

 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. [email protected]")]
      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; }

 }
问题回答
  1. 创建 < 坚固 > 查看器Base

    It implements the standard .net IDataErrorInfo. It works under WPF but should also work with Windows Forms.

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. Make Contact to Inherit of 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. Don t forget to put some validation trigger on controls to be validated
<TextBox Text="{Binding Path=Address,
                        UpdateSourceTrigger=PropertyChanged,                 
                        ValidatesOnDataErrors=True}" />
  1. Add some style to display an error tooltip on all textboxes
<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-atribite-validation" rel=“不跟随 noreferrerr>>https://github.com/EmmanuelDURIN/wpf-atritte-validation

灵感来自:

https://code.msdn.microsoft.com/windowsdesktop/validation-in-MVVM-using-12dafef3>https://code.msdn.microsoft.com/windowsdesktop/validation-in-MVM-using-12dafef3

实施顺利:-)

如果您想沿着这条路线走下去, 我建议您查看以下文章。 文章都围绕< a href=>, http://msdn. microsoft.com/ en- us/library/ system. improduct. idataerororinfo. aspx" rel = “ nofollow” @code>IDataErrorInfo 。

< a href=" "http://msdn.microsoft.com/en-us/library/bb909868.aspx" rel=“nofollow">MSDN:如何在自定义对象上执行验证逻辑

< a href=" "http://www.codeproject.com/articles/97564/Attlittes-based-validation-based-in-a-WPF- WPF-MVVM-Applicat" rel=“nofollow" >CodeProject:WPF MVVM 中基于属性的验证

从 WPF 4. 5 开始, 您可以在您的模型上执行 < code> I notififyDataErrorInfo , WPF 控制将约束于验证信息 。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签