WPF 无法将数据绑定(bind)到接口(interface)?

标签 wpf data-binding interface

我尝试将 WPF 表单中的控件绑定(bind)到接口(interface),但收到运行时错误,指出找不到接口(interface)的属性。

这是我用作数据源的类:

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 = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="402a242f25002c2936256e232f2d" rel="noreferrer noopener nofollow">[email protected]</a>";

this.DataContext = person;

请注意,我用作数据源的类需要是一个实体,因为我通过 entlib 的策略注入(inject)应用程序 block 使用策略注入(inject)。

我在运行时收到此错误:

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 的策略注入(inject),但我很确定你的问题就在那里,而不是因为你正在使用接口(interface)。
如果你要替换

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

IPerson person = new Person();

这肯定有用吗?

关于WPF 无法将数据绑定(bind)到接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75713/

相关文章:

c# - 当图像宽度超过 40,000 时渲染图像失败

c# - UI 进程的 WPF 加载动画

.net - WPF 中的依赖属性和附加属性有什么区别?

c# - c# win apps 中的用户控制和数据绑定(bind)

javascript - 使用 Angular 将数组从模板绑定(bind)到 Controller

c# - 如何正确返回接口(interface)列表类型?

wpf - 绑定(bind)属性上的 DataTrigger

c# - 数据绑定(bind)不刷新 Gridview

java - 为什么框架上没有画绳子?

c# - 当接口(interface)方法没有参数时,为什么不能识别具有所有可选参数的方法的实现?