Creating an instance of a nested class in XAML

自古美人都是妖i 提交于 2019-11-27 07:47:05
Ashley Grenon

I was searching and searching, because if this is possible, I would like to know. Unfortunately, I found this on msdn:

Your custom class must not be a nested class. Nested classes and the "dot" in their general CLR usage syntax interfere with other WPF and/or XAML features such as attached properties.

So, it appears you can't reference a nested class with the dot operator. As for alternative ways of getting to that inner class through XAML, I haven't had any luck in my searches yet. :o( But this is a rather interesting issue, so I will continue searching. Maybe I'll find some luck! :o)

This question is pretty old, and I don't know if it would have worked with the version of WPF back in 2010, but now you can make it work by using the "real" (internal) name of the nested type:

<local:A+B />

If you've ever looked a disassembled code, that's how nested types look like:

ParentTypeName+Nested

. refers to a property; not sure why XAML couldn't also search for a nested class, but it doesn't.


A nested class can be represented when inside a string (e.g. a property value), using A+B instead of A.B:

<Label SomeProperty1="{x:Static local:A+B.SomeProperty2}" />

As an element name (as shown in question), + is not allowed, as the result would no longer be valid XML; + is not a valid name character:
XAML is XML.
XML Spec - NameChar.

So the element name cannot directly describe a nested class.
BUT see UPDATE below - an alternative syntax that solves this.


UPDATE
Per @Artfunkel's comment on one answer, this should be a solution [I have not tested]:

<x:Type TypeName="local:A+B"/>

From: https://docs.microsoft.com/en-us/dotnet/framework/xaml-services/x-type-markup-extension

TBD how to specify properties with that syntax. Use x:TypeArguments?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!