wpf 从 MVVM 动态添加控件到 View
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14588082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically adding controls to View from MVVM
提问by boomchickawah
In WPF, I am using the MVVM model.
在 WPF 中,我使用的是 MVVM 模型。
I have a View with a Dockpanel and I want to add dynamically StackPanels with a Label and TextBox for all Harddisks found over the Binding.
我有一个带有 Dockpanel 的视图,我想为通过绑定找到的所有硬盘动态添加带有标签和文本框的 StackPanels。
Therefore my XAML looks like:
因此我的 XAML 看起来像:
<DockPanel Grid.Row="1" HorizontalAlignment="Stretch" Margin="5">
<ItemsControl ItemsSource="{Binding Harddisks}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel DockPanel.Dock="Right" HorizontalAlignment="Right" Margin="2.5,0,0,0">
<Label Content="{Binding Path=Label}" />
<TextBox Text="{Binding Path=GB_Free}" Width="100" IsReadOnly="True"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
It should be four Labels and TextBoxes, but only the first Label and TextBox are shown. Why?
应该是四个Labels和TextBoxes,但是只显示了第一个Label和TextBox。为什么?
回答by Duane
Your items in your ItemsControl are not actually direct children of the DockPanel. You need to change the ItemsControl to specify that the DockPanel is the Panel. The following will cause the ItemsControl to create a DockPanel and place all the items inside it (rather than the StackPanel that ItemsControl uses by default).
您在 ItemsControl 中的项目实际上并不是 DockPanel 的直接子项。您需要更改 ItemsControl 以指定 DockPanel 是面板。以下将导致 ItemsControl 创建一个 DockPanel 并将所有项目放在其中(而不是 ItemsControl 默认使用的 StackPanel)。
More Info: MSDN: ItemsControl.ItemsPanel Property
更多信息:MSDN:ItemsControl.ItemsPanel 属性
<ItemsControl ItemsSource="{Binding Harddisks}">
<ItemsControl.ItemsPanel>
<DockPanel Grid.Row="1" HorizontalAlignment="Stretch" Margin="5" />
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel DockPanel.Dock="Right" HorizontalAlignment="Right" Margin="2.5,0,0,0">
<Label Content="{Binding Path=Label}" />
<TextBox Text="{Binding Path=GB_Free}" Width="100" IsReadOnly="True"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>

