【发布时间】:2017-10-10 09:14:17
【问题描述】:
我有两个 xaml 代码行。
<TextBox Text="{Binding Path=MyEntity.Name, ValidatesOnDataErrors=True}" />
和
<ComboBox ItemsSource="{Binding EntityCollection}"
SelectedItem="{Binding Path=MyEntity.ChildEntity.NestedChildEntity}"
SelectedValue="{Binding Path=MyEntity.ChildEntity.ChildProperty, ValidatesOnDataErrors=True}"
SelectedValuePath="PK"/>
我所有的实体都通过一个基类 IDataErrorInfo 和他的索引器来实现。
MyEntity、ChildEntity 和 NestedChildEntity 是数据库实体。 MyEntity 具有到 ChildEntity 的导航属性。 ChildEntity 具有到 NestedChildEntity 的导航属性。 ChildProperty 在 ChildEntity 中是必需的。 ChildProperty 是外键,NestedChildEntity 是实体。如果我不在组合框中选择一个值,ChildProperty 将为空,通常它不能为空。
EntityCollection 是 List
类型MyEntity.cs
public class MyEntity : BaseEntityClass
{
[Key]
[Required]
public long PK { get; set; }
public string Name { get; set; }
public ChildEntity ChildEntity { get; set; }
}
ChildEntity.cs
public class ChildEntity : BaseEntityClass
{
[Key]
[Required]
public long PK { get; set; }
[Required]
public long ChildProperty { get; set; }
[ForeignKey("ChildProperty")]
public NestedChildEntity NestedChildEntity { get; set; }
}
NestedChildEntity.cs
public class NestedChildEntity : BaseEntityClass
{
[Key]
[Required]
public long PK { get; set; }
}
BaseEntityClass.cs
public class BaseEntityClass : IDataErrorInfo
{
public string Error
{
get
{
return null;
}
}
public string this[string propertyName]
{
get
{
//Check the Required and StringLength attribute
var annotationValidationError = GetAnnotationValidationError(propertyName);
if (annotationValidationError == null)
{
return GetValidationError(propertyName);
}
else
{
return annotationValidationError;
}
}
}
}
对于第一行,验证有效,到达我的基类中的索引器,并将属性名称作为参数发送(在本例中为“名称”)
对于第二行,验证永远不会到达。即使我的 ChildEntity 类实现(通过基类)IDataErrorInfo。
为什么嵌套绑定会有这样的行为?我该如何解决?
【问题讨论】:
标签: c# wpf validation data-binding