在Silverlight中添加UIElementCollection DependencyProperty
我想将一个依赖项属性添加到UserControl
,其中可以包含一组UIElement
对象。你可能会建议我应该从Panel
中得到我的控制权,并使用Children
属性,但对我来说这不是一个合适的解决方案。在Silverlight中添加UIElementCollection DependencyProperty
我已经修改了我的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
?如果是,建议使用的收集类是什么?
我改变属性的类型从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中使用另一个集合类型似乎没有任何问题。
如果您使用的是Silverlight Toolkit,则System.Windows.Controls.Toolkit程序集包含一个“ObjectCollection”,该对象旨在使XAML中的这类事情更容易完成。
这确实意味着你的属性需要是ObjectCollection类型才能工作,所以你失去了对UIElement的强类型输入。或者,如果它是IEnumerable类型(与大多数ItemsSource
一样),则可以在XAML中明确定义toolkit:ObjectCollection
对象。
考虑使用那个,或者简单地借用source to ObjectCollection(Ms-PL)并在项目中使用它。
可能有一种方法可以让解析器在集合场景中实际工作,但这种感觉更容易一些。
我还建议添加一个[ContentProperty]属性,以便设计时体验更清洁。
感谢您对“ContentProperty”(这不适用于我的情况)的输入和评论。 – 2009-08-19 16:16:53
更简单 - 很高兴它可以工作。当我尝试它时,我忘记将初始属性元数据设置为集合的一个实例。 – 2009-08-19 16:15:06