Trying to do something like this…
public class MiniObject
{
public bool Checked { get; set; }
public String Caption { get; set; }
public ICollection<MiniObject> Content { get; set;}
}
<Window.Resources>
<local:MiniObject x:Key="RootItem" Caption="Item0" Checked="True">
<local:MiniObject.Content>
<local:MiniObject Caption="Item1" Checked="True">
</local:MiniObject>
<local:MiniObject Caption="Item2" Checked="True">
</local:MiniObject>
</local:MiniObject.Content>
</local:MiniObject>
</Window.Resources>
This of course doesn’t work returning the error:
Object of type 'WorkflowTest.MiniObject' cannot be converted to type 'System.Collections.Generic.ICollection`1[WorkflowTest.MiniObject]'.
Is there a way to do this within WPF? If so do I need to change the shape of my objects at all or can I simply provide a specialized object that only WPF uses like…
<Window.Resources>
<local:MiniObject x:Key="RootItem" Caption="Item0" Checked="True">
<local:MiniObject.Content>
<local:MiniObjectCollection>
<local:MiniObject Caption="Item1" Checked="True">
</local:MiniObject>
<local:MiniObject Caption="Item2" Checked="True">
</local:MiniObject>
</local:MiniObjectCollection>
</local:MiniObject.Content>
</local:MiniObject>
</Window.Resources>
You’re trying to use XAML’s implicit collection syntax. In order to do this, the property (
Content, in this case) must be of a type that implementsICollection. Note: notICollection, but a type that implementsICollection.You can’t just use an interface because the
XamlReaderneeds to know what type of object to create. If you haven’t told it the type, how should it decide? By searching through all of the types available to your assembly, finding the ones that implementICollection<MiniObject>, discarding the ones that don’t have a parameterless constructor, and then choosing one at random? No.When you define
ContentasList<MiniObject>, theXamlReaderknows what type of object it should create. Since that’s a type that implementsICollection, it can use the implicit collection syntax. So it just creates the object and callsAddto add the child items, and if you stuck a child item in there that isn’t aMiniObjectyou’ll get a runtime error.You say that “I need to avoid using an actual implementation” in your
Contentproperty. In that case, you cannot use the implicit collection syntax. You will need to do what you do in your second example: explicitly define a type that implementsICollection<MiniObject>, and add a child element in your XAML to create it explicitly.