Search code examples
c#silverlightxamlsilverlight-3.0dependency-properties

Adding a UIElementCollection DependencyProperty in Silverlight


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?


Solution

  • I changed the type of my property from UIElementCollection to Collection<UIElement> and that seems to solve the problem:

    public partial class SilverlightControl1 : UserControl {
    
      public static readonly DependencyProperty ControlsProperty
        = DependencyProperty.Register(
          "Controls",
          typeof(Collection<UIElement>),
          typeof(SilverlightControl1),
          new PropertyMetadata(new Collection<UIElement>())
        );
    
      public Collection<UIElement> Controls {
        get {
          return (Collection<UIElement>) GetValue(ControlsProperty);
        }
      }
    
    }
    

    In WPF UIElementCollection has some functionality to navigate the logical and visual tree, but that seems to be absent in Silverlight. Using another collection type in Silverlight doesn't seem to pose any problem.