在Silverlight中添加UIElementCollection DependencyProperty

Mar*_*age 3 c# silverlight xaml dependency-properties silverlight-3.0

我想为UserControl可以包含UIElement对象集合的依赖项属性添加.您可能会建议我从中获取控件Panel并使用该Children属性,但在我的情况下它不是一个合适的解决方案.

我修改过UserControl这样的:

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);
    }
  }

}
Run Code Online (Sandbox Code Playgroud)

而我正在使用它:

<local:SilverlightControl1>
  <local:SilverlightControl1.Controls>
    <Button Content="A"/>
    <Button Content="B"/>
  </local:SilverlightControl1.Controls>
</local:SilverlightControl1>
Run Code Online (Sandbox Code Playgroud)

不幸的是,当我运行应用程序时出现以下错误:

Object of type 'System.Windows.Controls.Button' cannot be converted to type
'System.Windows.Controls.UIElementCollection'.
Run Code Online (Sandbox Code Playgroud)

在" 使用集合语法设置属性"部分中,明确声明:

[...]您无法在XAML中明确指定[UIElementCollection],因为UIElementCollection不是可构造的类.

我该怎么做才能解决我的问题?解决方案只是使用另一个集合类而不是UIElementCollection?如果是,建议使用的集合类是什么?

Mar*_*age 5

从我改变了我的属性的类型UIElementCollection,以Collection<UIElement>这似乎解决的问题:

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);
    }
  }

}
Run Code Online (Sandbox Code Playgroud)

在WPF中UIElementCollection有一些导航逻辑和可视树的功能,但在Silverlight中似乎没有.在Silverlight中使用另一种集合类型似乎没有任何问题.