I want to add a dependency property to a UserControl
that can contain a collection of UIElement
objects. You might suggest that I should derive my control from Panel
and use the Children
property for that, but it is not a suitable solution in my case.
I have modified my UserControl
like this:
public partial class SilverlightControl1 : UserControl {
public static readonly DependencyProperty ControlsProperty
= DependencyProperty.Register(
"Controls",
typeof(UIElementCollection),
typeof(SilverlightControl1),
null
);
public UIElementCollection Controls {
get {
return (UIElementCollection) GetValue(ControlsProperty);
}
set {
SetValue(ControlsProperty, value);
}
}
}
and I'm using it like this:
<local:SilverlightControl1>
<local:SilverlightControl1.Controls>
<Button Content="A"/>
<Button Content="B"/>
</local:SilverlightControl1.Controls>
</local:SilverlightControl1>
Unfortunately I get the following error when I run the application:
Object of type 'System.Windows.Controls.Button' cannot be converted to type
'System.Windows.Controls.UIElementCollection'.
In the Setting a Property by Using a Collection Syntax section it is explicitly stated that:
[...] you cannot specify [UIElementCollection] explicitly in XAML, because UIElementCollection is not a constructible class.
What can I do to solve my problem? Is the solution simply to use another collection class instead of UIElementCollection
? If yes, what is the recommended collection class to use?