在 WPF 中,我使用的是 MVVM 模型。
我有一个带有 Dockpanel 的视图,我想为通过绑定找到的所有硬盘动态添加带有标签和文本框的 StackPanels。
因此我的 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>
Run Code Online (Sandbox Code Playgroud)
应该是四个Labels和TextBoxes,但是只显示了第一个Label和TextBox。为什么?
您在 ItemsControl 中的项目实际上并不是 DockPanel 的直接子项。您需要更改 ItemsControl 以指定 DockPanel 是面板。以下将导致 ItemsControl 创建一个 DockPanel 并将所有项目放在其中(而不是 ItemsControl 默认使用的 StackPanel)。
更多信息: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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5892 次 |
| 最近记录: |