2
我需要在c-sharp wpf桌面應用程序中驗證一些用戶輸入。我正在使用實體框架和數據庫優先方法。這是由實體框架從數據庫中生成的類:數據庫優先和Wpf實體框架驗證
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>
屬性「名稱」的驗證不起作用。哪裏有問題?
您是否期望內置驗證功能可以使用?如果是這樣,它只適用於使用DbContext的情況。如果使用ObjectContext,則不支持驗證 – Pawel