C# 列表框项目之间的垂直间隙(删除??)
我的列表框是使用数据模板进行数据绑定的对象列表驱动的数据,例如:C# 列表框项目之间的垂直间隙(删除??),c#,xaml,listbox,win-universal-app,C#,Xaml,Listbox,Win Universal App,我的列表框是使用数据模板进行数据绑定的对象列表驱动的数据,例如: <ListBox x:Name="TheMainListBox" ScrollViewer.IsVerticalRailEnabled="True" ScrollViewer.IsHorizontalRailEnabled="False" HorizontalAlignment="Left"
<ListBox x:Name="TheMainListBox"
ScrollViewer.IsVerticalRailEnabled="True"
ScrollViewer.IsHorizontalRailEnabled="False"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Height="540"
ItemsSource="{Binding}"
Width="Auto"
Margin="0"
Padding="0"
Background="Yellow"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.VerticalScrollBarVisibility="Auto"
SelectionChanged="TheMainListBox_SelectionChanged"
DoubleTapped="TheMainListBox_DoubleTapped"
>
模板:
<ListBox.ItemTemplate>
<DataTemplate>
<Grid or Stackpanel Background="Blue"
Padding="0"
BorderBrush="Black"
BorderThickness="1"
Margin="0"
>
.... Binding Textboxes/blocks
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
.... 绑定文本框/块
我最终得到了一个黄色的容器,列表框。。列表框中有蓝色矩形,但它们之间有垂直间隙。我可以设置一个负的垂直顶部边距,但这是粗糙的,不适用于顶部项目。如何将项目之间的垂直间距减少到零
如果创建一个包含静态项的ListBox,则每个项都位于ListBoxItem容器中,例如:
<ListBoxItem BorderThickness="1" Width="100" Height="50"
BorderBrush="Black" Background="Red"/>
一切都按要求进行
那么如何使用ItemTemplate/DataBinding消除项目之间的垂直间距呢?
这是关键任务,提前使用thx。我没有想太多为什么会发生这种情况,也没有深入研究它的样式,我的答案看起来不太好,但请尝试
Margin=“0,-2,0,-2”
.... 绑定文本框/块
我没有时间加载项目进行测试,但您应该能够消除可能导致它的边距/填充。所以加上
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Padding" Value="0"/>
<Setter Property="Margin" Value="0"/>
</Style>
</ListBox.ItemContainerStyle>
正确设置ListBoxItem的高度将解决此问题。下面是代码片段
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Height" Value="Your_Desired_Height"/>
</Style>
</ListBox.ItemContainerStyle>
对于listbox,请使用Height属性;对于listview,请使用MinHeight属性。替换所需高度占位符中的所需高度值 垂直边距为负的问题是,顶部的项目可能会被截断或溢出到上面的元素。对于一个上下文,我尝试了Margin=“-12,-12,0,-12”,但我觉得这是一个太多的“修复”。@DavidJones,是的,这是一个修复。如果Chris W.的答案有效,那么就是它。@DavidJones当然,ItemTemplate就是通过嵌入ListBoxItem中的ContentPresenter显示的内容。另一方面,用于设置实际容器(即ListBoxItem本身及其样式模板)的样式。应用在ItemTemplate中,您实际上是ListBoxItem的子级。在ItemContainer中应用时,您是ListBoxItem的父级。希望这是有道理的。
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Height" Value="Your_Desired_Height"/>
</Style>
</ListBox.ItemContainerStyle>