Experts,
In XAML I would like to create a many-to-many relationship between entities.
Basically I would like for multiple “Manager” objects to be able to manage multiple “Items”. The following XAML should describe what I’m looking for:
<Grid>
<Grid.Resources>
<cc:Manager x:Key="Manager1"/>
<cc:Manager x:Key="Manager2"/>
</Grid.Resources>
<cc:Item>
<cc.Manager.ManagedBy>
<StaticResource ResourceKey="Manager1" />
</cc.Manager.ManagedBy>
</cc:Item>
<cc:Item>
<cc.Manager.ManagedBy>
<StaticResource ResourceKey="Manager1" />
<StaticResource ResourceKey="Manager2" /> <!-- ERROR HERE -->
</cc.Manager.ManagedBy>
</cc:Item>
<cc:Item>
<cc.Manager.ManagedBy>
<StaticResource ResourceKey="Manager2" />
</cc.Manager.ManagedBy>
</cc:Item>
</Grid>
The attached property (Manager.ManagedBy) is of type ManagedByCollection…
ManagedByCollection : List<ManageBy>
With this I get the following error message:
The object 'Object' already has a child and cannot add 'StaticResourceExtension'. 'Object' can accept only one child. Line NN Position NN.
So, I wen’t back to MSDN and realized there’s a ContentPropertyAttribute to tell the XAML compiler what property is the default one when nothing else is specified. The LinearGradientBrush, for example, uses that attribute to enable us to write just …
<LinearGradientBrush ... >
<GradientStop ... />
<GradientStop ... />
<GradientStop ... />
</LinearGradientBrush>
… instead of …
<LinearGradientBrush ... >
<GradientStopCollection>
<GradientStop ... />
<GradientStop ... />
<GradientStop ... />
</GradientStopCollection>
</LinearGradientBrush>
So, I was thinking I just needed to specify the indexer of ManagedByCollection as the class’ ContentProperty:
[ContentProperty("Item")
ManagerCollection : List<Manager>
Unfortunately, this does not resolve the issue. Currently the following works…
<cc.Manager.ManagedBy>
<ManagerCollection>
<StaticResource ResourceKey="Manager1" />
<StaticResource ResourceKey="Manager2" />
<cc:ManagerCollection>
</cc.Manager.ManagedBy>
… but, again, I would prefer the more readble syntax:
<cc.Manager.ManagedBy>
<StaticResource ResourceKey="Manager1" />
<StaticResource ResourceKey="Manager2" />
</cc.Manager.ManagedBy>
Any help or hints would be appreciated.
You can initialize the collection explicitly in the constructor of
Item: