水平列表框项目拉伸 [英] Horizontal ListBox Items Stretching
问题描述
我在WPF中的列表框有问题.首先,我有一个带有自定义ItemTemplate的水平ListBox.现在,我想拉伸项目,以使项目适合整个ListBox的宽度.我尝试了将HorizontalContentAlignment
设置为Stretch
的操作,但这仍然无法正常工作.
I have a problem with my ListBox in WPF. First of all, I have a horizontal ListBox with custom ItemTemplate. Now, I want to stretch the items, so that the items fits over the complete width of the ListBox. I tried things like setting the HorizontalContentAlignment
to Stretch
, but this still not working.
这是我的 ItemTemplate :
<DataTemplate x:Key="ListViewStepTemplate">
<Grid VerticalAlignment="Stretch">
<TextBlock Text="{Binding Path=Title}"
FontSize="15"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
<Image Height="16"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Bottom"
Source="/images/Content/check_16x16.png"
Visibility="{Binding Path=IsDone, Converter={StaticResource BooleantoVisibilityConverter}, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
</DataTemplate>
这是我的 ListBox :
And this is my ListBox:
<ListBox DockPanel.Dock="Top"
ItemsSource="{Binding AllItemsList}"
SelectedItem="{Binding CurrentItem}"
ItemTemplate="{StaticResource ListViewStepTemplate}"
Height="60"
HorizontalContentAlignment="Stretch">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="IsEnabled" Value="{Binding IsEnabled, UpdateSourceTrigger=PropertyChanged}" />
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="Padding" Value="30 0" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
如果有4个项目,则每个项目的宽度应为25%.如果有5个项目,则每个项目的宽度应为20%,依此类推.
If there are 4 items, each item should have a width of 25%. If there are 5 items, each item should have a width of 20% and so on.
可以做我想做的事吗?我现在尝试了很多事情,但是它永远无法正常工作.
Is it possible to do what I want to do? I tried a lot of things now, but it does never work.
推荐答案
不是使用StackPanel
而是使用UniformGrid
提供一种在网格中所有单元格都具有相同大小的网格中排列内容的方法.
Provides a way to arrange content in a grid where all the cells in the grid have the same size.
并将列数绑定到列表中的项目数,并禁用水平滚动功能.
and bind number of columns to number of items in the list and disable horizontal scrolling functionality.
<ListBox
...
ItemsSource="{Binding AllItemsList}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.VerticalScrollBarVisibility="Disabled" >
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="1" Columns="{Binding AllItemsList.Count}"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<!-- style -->
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
这篇关于水平列表框项目拉伸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!