【问题标题】:Adding a UIElementCollection DependencyProperty in Silverlight在 Silverlight 中添加 UIElementCollection DependencyProperty
【发布时间】:2009-08-19 11:56:23
【问题描述】:

我想向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);
    }
  }

}

我是这样使用它的:

<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'.

Setting a Property by Using a Collection Syntax 部分中明确指出:

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

我可以做些什么来解决我的问题?解决方案是否只是使用另一个集合类而不是UIElementCollection?如果是,推荐使用什么集合类?

【问题讨论】:

    标签: c# silverlight xaml silverlight-3.0 dependency-properties


    【解决方案1】:

    我将我的属性类型从UIElementCollection 更改为Collection&lt;UIElement&gt;,这似乎解决了问题:

    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 中使用其他集合类型似乎没有任何问题。

    【讨论】:

    • 更容易 - 很高兴它有效。当我尝试它时,我忘记将初始属性元数据设置为集合的实例。
    【解决方案2】:

    如果您使用的是 Silverlight Toolkit,则 System.Windows.Controls.Toolkit 程序集包含一个“ObjectCollection”,旨在使此类事情在 XAML 中更容易完成。

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

    考虑使用它,或者只是借用source to ObjectCollection (Ms-PL) 并在您的项目中使用它。

    可能有一种方法可以让解析器在集合场景中实际工作,但这感觉更容易一些。

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

    【讨论】:

    • 感谢您对ContentProperty(不适用于我的情况)的意见和好评。
    猜你喜欢
    • 2012-07-24
    • 1970-01-01
    • 2014-04-07
    • 1970-01-01
    • 1970-01-01
    • 2012-01-31
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    相关资源
    最近更新 更多