此问题可能与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";
}
}
使用以下XAML可以在ObjectDataProvider
上为BProperty
创建A
。
<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
的{{1}}设置为ObjectInstance
或"{x:Static Member=local:A.BProperty.CProperty}"
,我会收到编译错误。
如何从"{x:Static Member=local:A.BProperty+CProperty}"
访问CProperty
A
的{{1}}个实例上的BProperty
?
答案 0 :(得分:1)
你能做的最好的就是:
<Window.Resources>
<ObjectDataProvider x:Key="provider"
ObjectType="{x:Type local:A}"
MethodName="GetCValue">
<ObjectDataProvider.MethodParameters>
<System:String>string argument</System:String>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
public class A
{
public A()
{
BProperty = new B();
}
public B BProperty { get; private set; }
public string GetCValue(string arg)
{
return BProperty.CProperty.GetValue(arg);
}
}
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";
}
}
鉴于 ObjectDataProvider
的性质,我会远离这类实现中的静态如果要使用分层对象,请考虑实现MVVM模式并在ViewModel中实现所有对象。
有关ObjectDataProvider的更多详细信息,请查看此文章: http://msdn.microsoft.com/en-us/magazine/cc163299.aspx
答案 1 :(得分:1)
分两步完成:
<Window.Resources>
<ObjectDataProvider x:Key="providerOfC"
ObjectInstance="{x:Static Member=local:A.BProperty}"
MethodName="get_CProperty" />
<ObjectDataProvider x:Key="provider"
ObjectInstance="{StaticResource providerOfC}"
MethodName="GetValue">
<ObjectDataProvider.MethodParameters>
<System:String>string argument</System:String>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
<Grid>
<Label Content="{Binding Source={StaticResource provider}}" />
</Grid>
providerOfC
将您带到A.BProperty.CProperty
provider
然后在该实例上调用GetValue("string argument")
。