在WPF中使用几个子对象初始化的ObservableCollection属性 [英] ObservableCollection property initialized with a few children in WPF
问题描述
我们有一个WPF自定义控件,该控件具有名为 Persons
的 ObservableCollection< Person>
属性,一旦在WPF窗口上添加了自定义控件,生成的XAML就代表一个XAML行是我们的自定义控件.
We have a WPF custom control with an ObservableCollection<Person>
property called Persons
, once we add the custom control on the WPF window, the generated XAML represent a single XAML line of our custom control.
要使Persons集合的XAML已经包含一些项目(例如Paul,Sarah和John),我们需要做什么?
What do we need to do to have XAML of the Persons collection that already contains some items, like Paul, Sarah and John?
很长一段时间我们一直在研究如何成功实现这一目标.
It's a long time we study how to implement this without success.
谢谢.
我们现在所拥有的:
<MyCustomControl Height="228" Margin="45,30,0,0" Width="369" />
我们希望得到的:
<MyCustomControl Height="228" Margin="45,30,0,0" Width="369" />
<MyCustomControl.Persons>
<Person Name="Paul">
<Person Name="Sarah">
<Person Name="John">
</MyCustomControl.Persons>
</MyCustomControl>
推荐答案
只需将其添加到初始化中即可:
Just add it to the initialization:
public partial class CustomControl1 : UserControl
{
public CustomControl1(bool addDummies = false)
{
this.InitializeComponents();
this.Persons = new ObservableCollection<Person>();
if (addDummies)
{
this.Persons.Add(new Person() { Name = "Sarah" });
// etc
}
}
}
或者更好的是,也使用视图模型来绑定您的控件,并创建一个虚拟的视图模型以进行测试.传递那个而不是真实的视图模型.
Or better, use a view model to bind your control too, and create a dummy view model for testing purposes. Pass that one in instead of the real view model.
如果要将其添加到xaml,首先必须在标头中声明名称空间:
If you want to add it to the xaml, you first have to declare your namespace in the header:
xmlns:custom="clr-namespace:YourNamespace.InWhichThePersonClassIs"
然后在声明中使用它:
<custom:Person Name="Paul">
这篇关于在WPF中使用几个子对象初始化的ObservableCollection属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!