public interface IClassA
{
string Description { get; set; }
// more IClassA specific definitions
}
public interface IClassB
{
string Description { get; set; }
// more IClassB specific definitions
}
public class ClassA : IClassA
{
public string Description { get; set; }
}
public class ClassB : IClassB
{
public string Description { get; set; }
}
这是非常简化的代码。为简单起见,所有类都缺少INotifyPropertyChanged
实现。只需观看所有代码,就好像它已正确实现一样。
还不能考虑将Description
其放入基础接口中IClassA
,因此我对通过 WPF 中的数据绑定绑定的属性感到好奇。这就是我尝试过的:IClassB
dynamic
public class CustomClass
{
public dynamic Instance { get; set; }
// passed instance is a ClassA or ClassB object
public CustomClass(dynamic instance)
{
Instance = instance;
}
}
我的 Xaml 包含一个TextBlock
,它的 DataContext 设置为一个CutomClass
对象。如果我将Instance
属性的类型更改为例如 IClassA 并正确填充它,一切都会按预期工作。dynamic
虽然不是。
<TextBlock Text="{Binding Instance.Description}" />
VS2012 中的 Xaml Designer/ReSharper 告诉我:Cannot resolve property 'Description' in data context of type 'object'。
虽然CodeInstance
被描述为dynamic
. 但是编译的代码,所以我认为这可能是一个设计时问题。但TextBlock
仍然是空的。
我可能误解了这种情况下的原理dynamic
,我不知道。因此,使用 Google 搜索结果不足可能是由于不完全了解要搜索的内容造成的。