从ListBox项目选择中排除边距

时间:2014-04-15 05:18:04

标签: c# wpf listbox listboxitem

我有ListBox ...

<ListBox Margin="10" ItemsSource="{Binding Employees}" 
         ItemTemplate="{DynamicResource EmployeesTemplate}"
         HorizontalContentAlignment="Stretch" BorderThickness="0" 
         ScrollViewer.CanContentScroll="False"/>

...有自定义DataTemplate

<Window.Resources>
    <DataTemplate x:Key="EmployeesTemplate">
        <Border BorderThickness="1" BorderBrush="Black" SnapsToDevicePixels="True"
                DockPanel.Dock="Top" Margin="0,0,0,5" Padding="5">
            <StackPanel>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="150"/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <StackPanel Grid.Column="0" Orientation="Horizontal">
                        <TextBlock Text="{Binding Path=FirstName}" Padding="0,0,5,0"/>
                        <TextBlock Text="{Binding Path=LastName}"/>
                    </StackPanel>
                    <TextBlock Grid.Column="1" Text="{Binding Path=Title}"/>
                </Grid>
                <StackPanel>
                    <TextBlock Text="{Binding Path=DateOfBirth, StringFormat={}{0:MM/dd/yyyy}}"/>
                    <TextBlock Text="{Binding Path=Address}"/>
                    <TextBlock Text="{Binding Path=PhoneNumber}"/>
                    <TextBlock Text="{Binding Path=Salary, StringFormat={}{0:C}}"/>
                </StackPanel>
            </StackPanel>
        </Border>
    </DataTemplate>
</Window.Resources>

当我从ListBox中选择一个项目时,选择突出显示包括分配到每个项目底部的{5} Margin Border DataTemplate ):

enter image description here

您会注意到左侧的类似情况,其中突出显示稍微溢出。直到现在我才注意到......嗯。因此,我想将选择突出显示限制在边框区域,而不在其外部,并且能够保留项目之间的边距。

我将如何实现这一目标?我尽可能多地操纵PaddingMargin,但我无法理解。也许我必须创建自定义ListBox template

1 个答案:

答案 0 :(得分:0)

我不确定是否有更简单的方法,但它对我有用。我在DataTemplate.Triggers ...

中添加了DataTemplate部分
<DataTemplate.Triggers>
    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, 
                         AncestorType={x:Type ListBoxItem}}, Path=IsMouseOver}" Value="True">
        <Setter Property="Background" Value="LightBlue" TargetName="EmployeesTemplateBorder"/>
    </DataTrigger>

    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, 
                         AncestorType={x:Type ListBoxItem}}, Path=IsSelected}" Value="True">
        <Setter Property="Background" Value="RoyalBlue" TargetName="EmployeesTemplateBorder"/>
    </DataTrigger>
</DataTemplate.Triggers>

...以及ListBox.Resrouces的{​​{1}}部分(摆脱默认突出显示行为):

ListBox

显然,这对前景没有任何作用,但这不是现在关注的问题,因为与这个突出例程相比,这个问题相对容易。