绑定到child时IDataErrorInfo不起作用

时间:2017-10-10 09:14:18

标签: c# wpf validation data-binding

我有两个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 的导航属性。 ChildEntity中需要 ChildProperty ChildProperty 是外键, NestedChildEntity 是实体。如果我没有在组合框中选择一个值, ChildProperty 将为null,通常它不能为null。

EntityCollection 的类型为列表&lt; NestedChildEntity&gt;

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

对于第一行,验证工作,我的基类中的索引器已到达,属性名称作为参数发送(在本例中为“Name”)

对于第二行,验证永远不会到达。即使我的 ChildEntity 类实现(通过基类)IDataErrorInfo。

为什么这种行为与嵌套绑定?我该如何解决?

2 个答案:

答案 0 :(得分:0)

为什么你绑定StringSelectedItem? <永远不会设置SelectedValue属性。

如果SelectedValue属性返回的对象实现了NestedChildEntity接口,并且该对象的类型与IDataErrorInfo中的项类型相匹配,那么这应该有效:

EntityCollection

答案 1 :(得分:-1)

好的,我终于找到了解决方案。

以前,在我的视图模型构造函数中,我初始化了我的MyEntity属性,如下所示:

MyEntity = new MyEntity ();

问题是我的 {Binding Path=MyEntity.ChildEntity.ChildProperty} MyEntity 中的 ChildEntity 未初始化。

我将构造函数更改为:

MyEntity = new MyEntity { ChildEntity = new ChildEntity() };

现在一切正常!

你的帮助@ mm8