代码之家  ›  专栏  ›  技术社区  ›  Martin Liversage

在Silverlight中添加UIElementCollection依赖属性

  •  3
  • Martin Liversage  · 技术社区  · 16 年前

    我想向 UserControl UIElement Panel Children 财产,但就我而言,这不是一个合适的解决方案。

    用户控件

    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

    2 回复  |  直到 16 年前
        1
  •  5
  •   Martin Liversage    16 年前

    我更改了我的房产类型 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中 有一些功能可以导航逻辑和视觉树,但Silverlight中似乎没有。在Silverlight中使用另一种集合类型似乎不会造成任何问题。

        2
  •  1
  •   Jeff Wilcox    16 年前

    如果你正在使用 Silverlight Toolkit ,系统。窗户。控制。Toolkit程序集包含一个“ObjectCollection”,旨在使XAML中的此类操作更容易完成。

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

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

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

    我还建议添加一个[CntentProperty]属性,这样设计时的体验会更清晰一些。

    推荐文章