Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将自定义控件的ObservableCollection绑定到StackPanel?_C#_Wpf_Data Binding_Custom Controls_Stackpanel - Fatal编程技术网

C# 如何将自定义控件的ObservableCollection绑定到StackPanel?

C# 如何将自定义控件的ObservableCollection绑定到StackPanel?,c#,wpf,data-binding,custom-controls,stackpanel,C#,Wpf,Data Binding,Custom Controls,Stackpanel,我有一个可观察的自定义控件对象集合 ObservableCollection MyUIObjects=新的ObservableCollection() 自定义控件是这样的用户控件 public分部类MyStatusBar:UserControl,INotifyPropertyChanged 将控件列表绑定到stackpanel以显示它们的最简单方法是什么。当前,当我绑定它们时,没有显示任何内容。当我将控件手动添加到StackPanel.Children集合中时,它们会显示出来,但我希望使用绑定来

我有一个可观察的自定义控件对象集合

ObservableCollection MyUIObjects=新的ObservableCollection()

自定义控件是这样的用户控件

public分部类MyStatusBar:UserControl,INotifyPropertyChanged


将控件列表绑定到stackpanel以显示它们的最简单方法是什么。当前,当我绑定它们时,没有显示任何内容。当我将控件手动添加到StackPanel.Children集合中时,它们会显示出来,但我希望使用绑定来执行此操作。

请查看代码片段。 将Itemcontrol替换为任何Itemscontrol,如listbox等,否则您仍然可以使用Itemscontrol吗

<ItemsControl ItemsSource="{Binding MyUIObjects}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

MyStatusBar
不应该是
用户控件,而应该是POCO:

public class MyStatusBar : INotifyPropertyChanged { ... }
然后,您可以使用
ItemsControl
绑定到
ObservableCollection
并定义
itemstemplate
,在其中放置要为每个POCO对象呈现的
UserControl

<ItemsControl ItemsSource="{Binding MyUIObjects}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <local:MyStatusBarUserControl />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

ItemsPanelTemplate
指定
ItemsPresenter
ItemsControl
中的项目布局创建的面板(在本例中为
StackPanel


请注意,
MyStatusBar
MyStatusBarUserControl
是不同的类型。视图模型不应创建或公开UI元素。它应该公开数据对象。然后使用
ItemTemplate

请为每个数据对象创建一个UI元素,共享您的绑定和xamlcode@daniel使用itemscontrol绑定自定义对象,并设置面板类型stackpanel以显示自定义对象的集合。要绑定到工作
MyUIObjects
必须是:
public observeCollection MyUIObjects{get;}=new observeCollection()在UserControl中实现INotifyPropertyChanged也是一个值得怀疑的想法。仅使用DependencyProperties—它们具有内置的通知支持—而且更多ItemsControl默认使用垂直虚拟化StackPanel。明确地将
分配给ItemsPanel@ash你说得对。这段代码只是一个如何绑定可观察集合而不是完整解决方案的示例。