【发布时间】:2012-07-19 20:43:36
【问题描述】:
此问题可能与Creating an instance of a nested class in XAML 重复。这个问题和相关的 MSDN 文档都与嵌套类型有关。在这个例子中,类型本身没有嵌套,但语法看起来很熟悉。我不知道这是否证明单独的问题和答案是合理的。
我想使用ObjectDataProvider 访问嵌套属性。我可以访问类型的静态属性,但通过类型的静态属性访问实例属性会导致编译错误。
例如,取以下三个类。
public static class A
{
static A()
{
BProperty = new B();
}
public static B BProperty { get; private set; }
}
public class B
{
public B()
{
CProperty = new C();
}
public C CProperty { get; private set; }
public string GetValue(string arg)
{
return arg + " from B";
}
}
public class C
{
public string GetValue(string arg)
{
return arg + " from C";
}
}
在A 上为BProperty 创建一个ObjectDataProvider 可以使用以下XAML 完成。
<Window.Resources>
<ObjectDataProvider x:Key="provider"
ObjectInstance="{x:Static Member=local:A.BProperty}"
MethodName="GetValue">
<ObjectDataProvider.MethodParameters>
<System:String>string argument</System:String>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
<Grid>
<Label Content="{Binding Source={StaticResource provider}}" />
</Grid>
运行此代码会生成一个带有文本的标签:“来自 B 的字符串参数”。
如果我将provider 的ObjectInstance 设置为"{x:Static Member=local:A.BProperty.CProperty}" 或"{x:Static Member=local:A.BProperty+CProperty}",我会收到编译错误。
如何从ObjectDataProvider 访问A 的BProperty 实例上的CProperty?
【问题讨论】:
-
你的类名和属性名是一样的。为了测试,你可以重命名你的类,看看它是否仍然出现?
-
这个例子是从我的原始代码简化而来的,它的属性名称与它们的返回类型不同。在这种情况下,问题仍然存在。但是,它可能会提高此示例的可读性,因此我将更新代码。
-
我会说这是因为 B 被实例化为静态的。因此,一旦它被实例化,它的上下文属性就会被忽略。
标签: wpf xaml objectdataprovider nested-properties