我的WPF应用程序有一个ListBox
,其ItemTemplate
如下所示:
<DataTemplate x:Key="DomainTemplate" DataType="DomainViewModel">
<Border BorderBrush="{Binding Converter={StaticResource BrushConverter}, Path=IsSelected}"
BorderThickness="3"
Grid.Column="0"
Name="SelectedBorder"
Padding="5">
<Button Click="SelectDomain_Click"
FontSize="16"
FontWeight="Bold"
IsEnabled="{Binding Path=CurrentSiteIsValid, RelativeSource={RelativeSource AncestorType={x:Type c:DomainPicker}}}"
MinHeight="60"
Tag="{Binding Path=DomainId}"
Width="120">
<TextBlock Text="{Binding Path=Name}"
TextAlignment="Center"
TextWrapping="WrapWithOverflow" />
</Button>
</Border>
</DataTemplate>
窗口的宽度由ListBox
的宽度驱动。这是经过设计的。在ListBox
的垂直边缘和其中的项目之间似乎有很大的空间。使用Snoop,我看到ListBoxItem
包含一个与ListBox
宽度相同的Border
,Margin
为0,Padding
设置为2,0,0,0。
Border
包含一个ContentPresenter
,其宽度比包含它的Border
小29个单位。Border
上的Padding
似乎占了其中的2个单位。其Margin
为0,并且不具有填充属性。
如果可以的话,我实际上想把这个窗口缩小一点,而不让模板中的Buttons
变窄。那29个单元的空间是从哪里来的?有办法改变它的尺寸吗?
我也遇到过这个问题,在这个问题中,我使用了WrapPanel作为ListBox的ItemPanel,在某些情况下,由于您提到的问题,我的项目之间出现了间隙。修复方法如下:
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Padding" Value="0"/>
</Style>
</ListBox.ItemContainerStyle>