Creating an instance of a nested class in XAML

2019-01-11 03:05发布

问题:

in a XAML file (a WPF UserControl), is there a way to reference an inner class "B" defined in another class "A" ?

public class A
{
    public class B
    {
    }
}

Something like :

<local:A.B ... />

This syntax does not work because "B" is interpreted as a property named "B" in class "A".

I've tried more exotic syntaxes like "::" or "+" but none seems to work.

I'm currently using Silverlight 4 with VS2010.

Thanks in advance for your help.

回答1:

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)



回答2:

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


回答3:

. 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?