1
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 中的数据绑定绑定的属性感到好奇。这就是我尝试过的:IClassBdynamic

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 搜索结果不足可能是由于不完全了解要搜索的内容造成的。

4

1 回答 1

3

您可以像绑定任何属性一样绑定到动态属性。所以你的问题必须在其他地方表现出来,或者ReSharper给出另一个无益的错误,(讨厌那个程序)

动态绑定示例:

xml:

<Window x:Class="WpfApplication7.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="104" Width="223" Name="UI">
    <StackPanel DataContext="{Binding ElementName=UI}">
        <TextBlock Text="{Binding MyProperty}" />
        <TextBlock Text="{Binding MyObject.MyProperty}" />
    </StackPanel>
</Window>

代码:

public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();
        MyProperty = "Hello";
        MyObject = new ObjectTest { MyProperty = "Hello" };
    }

    private dynamic myVar;
    public dynamic MyProperty
    {
        get { return myVar; }
        set { myVar = value; NotifyPropertyChanged("MyProperty"); }
    }

    private dynamic myObject;
    public dynamic MyObject
    {
        get { return myObject; }
        set { myObject = value; NotifyPropertyChanged("MyObject"); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(string p)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(p));
        }
    }
}

public class ObjectTest
{
    public string MyProperty { get; set; }
}

结果:

在此处输入图像描述

于 2013-02-14T01:33:23.933 回答