2

我需要在 c-sharp wpf 桌面应用程序中验证一些用户输入。我正在使用具有数据库优先方法的实体框架。这是 Entity 框架从数据库生成的类:

namespace TestValidation
{
    using System;
    using System.Collections.Generic;

    public partial class person
    {
        public string Name { get; set; }
        public string Surname { get; set; }
    }
}

我正在尝试使用带有 DataAnnotations 的伙伴类来实现验证:

using System.ComponentModel.DataAnnotations;

    namespace TestValidation
    {
        [MetadataType(typeof(person_validation))]
        public partial class person
        {
            public class person_validation
            {
                [Required]
                public string Name { get; set; }
            }
        }
    }

这是我的 xaml 表单:

<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:TestValidation" mc:Ignorable="d" x:Class="TestValidation.MainWindow"
        Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded_1">
    <Window.Resources>
        <CollectionViewSource x:Key="personViewSource" d:DesignSource="{d:DesignInstance {x:Type local:person}, CreateList=True}"/>
    </Window.Resources>
    <Grid>
        <Grid x:Name="grid1" DataContext="{StaticResource personViewSource}" HorizontalAlignment="Left" Margin="129,95,0,0" VerticalAlignment="Top">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <Label Content="Name:" Grid.Column="0" HorizontalAlignment="Left" Margin="3" Grid.Row="0" VerticalAlignment="Center"/>
            <TextBox x:Name="nameTextBox" Grid.Column="1" HorizontalAlignment="Left" Height="23" Margin="3" Grid.Row="0" Text="{Binding Name, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" VerticalAlignment="Center" Width="120"/>
        </Grid>
        <Button Content="Button" HorizontalAlignment="Left" Margin="162,217,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>

    </Grid>
</Window>

属性“名称”的验证不起作用。问题出在哪里?

4

1 回答 1

0

这篇文章:

在 WPF 中,与 Silverlight 不同的是,组件 (DataGrid) 不会自动读取数据注释。您必须实现 IDataErrorInfo 接口并使用数据注释手动验证。

于 2013-01-26T10:19:20.053 回答