【问题标题】:How to bind an observable collection to an array of user controls?如何将可观察集合绑定到用户控件数组?
【发布时间】:2010-11-18 13:24:24
【问题描述】:
WPF 中的数据绑定很棒,但是当您尝试让事情变得更复杂时,实现起来就变得异常困难。
我有一个对象集合,其中每个对象都有绑定到用户控件的可观察属性。
我想(理想情况下)简单地将一个新对象添加到我的集合中,并在我的表单上显示一个新的用户控件。问题是用户控件需要动态创建,所以每次我添加到集合中时,我可能必须手动创建一个新控件,设置绑定并将其添加到我的窗口中。有没有更简单的 MVVM 风格的方式绑定到这样的结构?
【问题讨论】:
标签:
wpf
data-binding
mvvm
observablecollection
【解决方案1】:
使用ItemsControl 和DataTemplate
<ItemsControl ItemsSource="{Binding YourCollection}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<uc:YourUserControl />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>