从 wpf 客户端验证视图模型中的实体框架对象
本文关键字:实体 框架 对象 模型 wpf 客户端 验证 视图 | 更新日期: 2024-11-03 16:57:42
在我的WPF MVVM-Light ViewModel类中,我有一个属性,它是来自EntityFramework 6的EntityObject
。 public Client Client
{
get { return client; }
set
{
client = value;
this.RaisePropertyChanged(() => this.Client);
}
}
客户端类的部分部分:
[MetadataType(typeof(ClientMetadata))]
[CustomValidation(typeof(ClientValidator), "ClientValidation")]
public partial class Client
{
public sealed class ClientMetadata
{
[Display(ResourceType = typeof(CaptionResources), Name = "Name")]
public string Name { get; set; }
}
}
它绑定到视图中的许多控件,例如:
<TextBox TextWrapping="Wrap" Margin="5" Height="36" Text="{Binding Client.Name, Mode=TwoWay, ValidatesOnDataErrors=True, NotifyOnValidationError=True, NotifyOnSourceUpdated=True}" TabIndex="1"
Validation.ErrorTemplate="{StaticResource ImagedErrorTemplate}"/>
如何在视图上显示验证结果?我已经在我的视图模型中实现了INotifyDataErrorInfo, IValidationErrors
接口。我已经有一个验证对象并返回验证错误的方法:
private bool Validate()
{
var errors = new Dictionary<string, string>();
if (!IsValid<Client, Client.ClientMetadata>(this.Client, ref errors))
{
foreach (var error in errors)
{
this.RaiseErrorsChanged("Client." + error.Key);
this.RaisePropertyChanged(string.Format("Client.{0}", error.Key));
}
return false;
}
return true;
}
但我仍然无法在视图中获得此信息。我的错误模板适用于"标准"属性:
<ControlTemplate x:Key="ImagedErrorTemplate">
<DockPanel >
<Border BorderBrush="Red" BorderThickness="1">
<AdornedElementPlaceholder x:Name="adorner"/>
</Border>
<Image Source="../Assets/Images/warning.png"
Height="20"
Width="20"
ToolTip="{Binding ElementName=adorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"/>
</DockPanel>
</ControlTemplate>
有没有办法在没有DTO对象的情况下做到这一点?
提前谢谢。
我通过在 EntityFramework 对象上实现 INotifyDataErrorInfo 来做到这一点。
[MetadataType(typeof(ClientMetadata))]
[CustomValidation(typeof(ClientValidator), "ClientValidation")]
public partial class Client : INotifyDataErrorInfo
{
private Dictionary<string, ICollection<string>> validationErrors = new Dictionary<string, ICollection<string>>();
public sealed class ClientMetadata
{
[Display(ResourceType = typeof(CaptionResources), Name = "Name")]
public string Name { get; set; }
}
public Dictionary<string, ICollection<string>> ValidationErrors
{
get
{
return this.validationErrors;
}
set
{
this.validationErrors = value;
}
}
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
public IEnumerable GetErrors(string propertyName)
{
if (string.IsNullOrEmpty(propertyName) || !this.ValidationErrors.ContainsKey(propertyName))
{
return null;
}
return this.ValidationErrors[propertyName];
}
public bool HasErrors
{
get { return this.ValidationErrors.Count > 0; }
}
public void RaiseErrorsChanged(string propertyName)
{
if (this.ErrorsChanged != null)
{
this.ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
}
}