WPF无法数据绑定到接口吗?

时间:2020-03-05 18:56:51  来源:igfitidea点击:

我试图将WPF形式的控件绑定到接口,但遇到运行时错误,提示它找不到接口的属性。

这是我用作数据源的类:

public interface IPerson
{
    string UserId { get; set; }
    string UserName { get; set; }
    string Email { get; set; }
}

public class Person : EntityBase, IPerson
{
    public virtual string UserId { get; set; }
    public string UserName { get; set; }
    public virtual string Email { get; set; }
}

这是XAML(摘录):

<TextBox Name="userIdTextBox" Text="{Binding UserId}" />
<TextBox Name="userNameTextBox" Text="{Binding UserName}" />
<TextBox Name="emailTextBox" Text="{Binding Email}" />

这是背后的代码(再次摘录):

var person = PolicyInjection.Wrap<IPerson>(new Person());
person.UserId = "jdoe";
person.UserName = "John Doe";
person.Email = "[email protected]";

this.DataContext = person;

请注意,我用作数据源的类必须是一个实体,因为我通过entlib的Policy Injection Application Block使用Policy Injection。

我在运行时遇到此错误:

System.Windows.Data Error: 16 : Cannot get 'Email' value (type 'String') from '' (type 'Person'). BindingExpression:Path=Email; DataItem='Person' (HashCode=22322349); target element is 'TextBox' (Name='emailTextBox'); target property is 'Text' (type 'String') TargetException:'System.Reflection.TargetException: Object does not match target type.
   at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
   at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index)
   at MS.Internal.Data.PropertyPathWorker.GetValue(Object item, Int32 level)
   at MS.Internal.Data.PropertyPathWorker.RawValue(Int32 k)'

解决方案

回答

我不熟悉entlib的策略注入,但是我很确定问题就在这里,而不是因为我们使用的是接口。
如果要更换

var person = PolicyInjection.Wrap<IPerson>(new Person());

IPerson person = new Person();

肯定会起作用吗?

回答

我认为代码没有太多错误。从技术上讲,我们正在绑定Person类的实例(即无论如何尝试都没有必要绑定到接口)我不知道PolicyInjection.Wrap方法会做什么,但是我假设它返回了一个具体的人类?无论如何,我只是尝试了一下,效果很好...

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();

        IPerson person = new Person() { FirstName = "Hovito" };

        this.DataContext = person;
    }
}

public class Person : IPerson
{
    public virtual string FirstName { get; set; }
    public string LastName { get; set; }
}

public interface IPerson
{
    string FirstName { get; set; }
    string LastName { get; set; }
}

我建议我们多研究一下PolicyInjection类。找出它是否确实返回了我们所期望的Person类型。

回答

除了项目中的接口外,我们几乎没有绑定任何东西,而一切都没有问题。我们遇到的问题归因于entlib ...但是我对entlib不够了解,无法在那里为我们提供帮助。但是,WPF可以绑定到接口。