正确地水平包裹TextBlocks :
<StackPanel DockPanel.Dock="Top" Margin="10" HorizontalAlignment="Left">
<TextBlock Text="Simple WrapPanel:" Margin="0 0 0 5"/>
<WrapPanel Orientation="Horizontal">
<TextBlock Text="one"/>
<TextBlock Text="two"/>
<TextBlock Text="thee"/>
<TextBlock Text="four"/>
</WrapPanel>
</StackPanel>
但是错误地将我的UserControls垂直堆叠在彼此之上(我希望它们像上面的TextBlocks一样水平包裹):
<StackPanel DockPanel.Dock="Top" Margin="10" HorizontalAlignment="Left">
<TextBlock Text="Simple WrapPanel:" Margin="0 0 0 5"/>
<WrapPanel Orientation="Horizontal">
<ItemsControl ItemsSource="{Binding CustomerViewModels}" Width="Auto" BorderThickness="0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<views:CustomerSimpleItemView />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</WrapPanel>
</StackPanel>
CustomerSimpleItemView:
<UserControl x:Class="TestMvvmExample2341.Views.CustomerSimpleItemView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<TextBlock Text="{Binding LastName}" FontWeight="Bold" Width="100"/>
</UserControl>
我在UserControl中需要做什么才能横向包裹?
添加:即使我将usercontrol中的所有宽度和高度更改为Auto,它仍然会垂直堆叠......:
<UserControl x:Class="TestMvvmExample2341.Views.CustomerSimpleItemView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="Auto" Height="Auto">
<TextBlock Text="{Binding LastName}" FontWeight="Bold" Width="Auto" Height="Auto"/>
</UserControl>
答案 0 :(得分:9)
在第二个示例中,尝试使用ItemsPanelTemplate中的WrapPanel作为ItemsControl,否则ItemsControl默认使用StackPanel,而WrapPanel不会执行任何操作,因为没有任何内容可以包装。
<StackPanel DockPanel.Dock="Top" Margin="10" HorizontalAlignment="Left">
<TextBlock Text="Simple WrapPanel:" Margin="0 0 0 5"/>
<ItemsControl ItemsSource="{Binding CustomerViewModels}" Width="Auto" BorderThickness="0">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<views:CustomerSimpleItemView />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
答案 1 :(得分:3)
发生这种情况是因为ItemsControl默认使用垂直方向的StackPanel来布局子对象。因此,包装面板实际上只布置了一个子项,即ItemsControl。你不想做的是设置ItemsControl的ItemsPanel属性,以便使用WrapPanel进行布局。你的代码看起来像这样:
<StackPanel DockPanel.Dock="Top"
Margin="10"
HorizontalAlignment="Left">
<TextBlock Text="Simple WrapPanel:"
Margin="0 0 0 5" />
<!-- Note I am removing the WrapPanel that was surrounding the ItemsControl -->
<ItemsControl ItemsSource="{Binding CustomerViewModels}"
Width="Auto"
BorderThickness="0">
<!-- This is the important part. Here we set the ItemsPanel template -->
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<views:CustomerSimpleItemView />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>