在Silverlight中添加一个UIElementCollection DependencyProperty

3
我想要为一个可以包含UIElement对象集合的UserControl添加一个依赖属性。你可能会建议我从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);
    }
  }

}

我这样使用它:

<local:SilverlightControl1>
  <local:SilverlightControl1.Controls>
    <Button Content="A"/>
    <Button Content="B"/>
  </local:SilverlightControl1.Controls>
</local:SilverlightControl1>

很遗憾,当我运行应用程序时,出现了以下错误:
Object of type 'System.Windows.Controls.Button' cannot be converted to type
'System.Windows.Controls.UIElementCollection'.

使用集合语法设置属性一节中明确指出:

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

我该怎么办才能解决我的问题?解决方案是否只是使用另一个集合类代替UIElementCollection?如果是,推荐使用哪个集合类?
2个回答

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

}

在WPF中,UIElementCollection具有一些导航逻辑和视觉树的功能,但在Silverlight中似乎缺少这些功能。在Silverlight中使用另一种集合类型似乎并不会出现任何问题。

更简单了 - 很高兴它能工作。当我尝试时,我忘记将初始属性元数据设置为集合的实例。 - Jeff Wilcox

1

如果您正在使用Silverlight Toolkit,则System.Windows.Controls.Toolkit程序集包含一个“ObjectCollection”,旨在使在XAML中执行此类操作更加容易。

这意味着您的属性需要是ObjectCollection类型才能工作,因此您会失去对UIElement的强类型控制。或者,如果它是IEnumerable类型(像大多数ItemsSource一样),您可以在XAML中明确定义toolkit:ObjectCollection对象。

考虑使用它,或者只需借用源代码到ObjectCollection(Ms-PL)并在项目中使用它。

可能有一种方法可以使解析器在集合场景中实际工作,但这感觉有点困难。

我还建议添加[ContentProperty]属性,以使设计时体验更加清晰。


感谢您对ContentProperty的输入和好评(但在我的情况下不适用)。 - Martin Liversage

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接