首页 > 解决方案 > WPF 窗口不显示基类的属性

问题描述

我有一个包含公共属性MyDictionary的类:

Public MustInherit Class MyBaseClass
    Public Shared ReadOnly Property MyDictionary As Dictionary(Of Integer, String)
        Get
            Return New Dictionary(Of Integer, String) From {
                {0, "Option 1"},
                {1, "Option 2"}
            }
        End Get
    End Property
End Class

这个类是少数子类的基类,例如ClassAClassB。正如预期的那样,属性MyDictionary()由子类继承,但请注意,它是静态的。

另外,我还有一个 XAML 标记,控件的 DataContext 是其中一个子类的实例:

<Window>
    <Grid DataContext="{Binding ClassA}">
        <ComboBox ItemsSource="{Binding MyDictionary.Values}" />
    </Grid>
</Window>

问题是在运行时窗口包含空白组合框。错误描述是:

System.Windows.Data 错误:39:BindingExpression 路径错误:在“对象”“ClassA”(HashCode=9490272)上找不到“MyDictionary”属性。BindingExpression:Path=MyDictionary.Values; DataItem='ClassA' (HashCode=9490272); 目标元素是 'ComboBox' (Name=''); 目标属性是“ItemsSource”(类型“IEnumerable”)

如果我将 MyDictionary()属性显式覆盖到ClassA中,问题就消失了,ComboBox 控件包含项目“选项 1”和“选项 2”。

两个问题。

  1. 为什么我需要在每个子类中创建属性以将其用作控件的项目源?为什么 XAML 不能使用基类的属性?否则就失去了继承的价值。
  2. 有没有办法使用基类的属性作为项目源?

标签: wpfvb.netinheritancedata-binding

解决方案


推荐阅读