我想向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
吗?如果是,建议使用的集合类是什么?
答案 0 :(得分: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中使用另一种集合类型似乎没有任何问题。
答案 1 :(得分:1)
如果您正在使用Silverlight Toolkit,则System.Windows.Controls.Toolkit程序集包含一个“ObjectCollection”,旨在使这种事情在XAML中更容易实现。
这确实意味着您的属性需要使用ObjectCollection类型才能工作,因此您失去了对UIElement的强类型。或者,如果它是IEnumerable类型(与大多数ItemsSource
一样),则可以在XAML中显式定义toolkit:ObjectCollection
对象。
考虑使用它,或者只是借用source to ObjectCollection(Ms-PL)并在项目中使用它。
可能有一种方法可以让解析器在集合场景中实际工作,但这感觉更容易一些。
我还建议添加[ContentProperty]属性,以便设计时体验更清晰。