Is it possible to emulate border-collapse (ala CSS) in a WPF ItemsControl?

后端 未结 3 1418
执念已碎
执念已碎 2021-02-13 11:28

I\'m styling the items in a WPF ListBox, and want to put a border around each item. With BorderThickness set to 1, for example, the top-bottom borders

相关标签:
3条回答
  • 2021-02-13 12:08

    One thing that comes to mind is to make use of AlternationIndex. This will require you to set something like AlternationCount="10000" on the ListBox. After that you can set BorderThickess="1,0,1,1" and use a DataTrigger to find the first ListBoxItem

    <DataTemplate>
      <Border x:Name="border" BorderThickness="1,0,1,1" BorderBrush="DarkSlateGray" Background="DimGray" Padding="8 4 8 4">        
        <TextBlock Text="{Binding Name}" FontSize="16"/>
      </Border>
      <DataTemplate.Triggers>
        <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}},
                                       Path=(ItemsControl.AlternationIndex)}"
                     Value="0">
          <Setter TargetName="border" Property="BorderThickness" Value="1,1,1,1"/>
        </DataTrigger>
      </DataTemplate.Triggers>
    </DataTemplate>
    
    0 讨论(0)
  • 2021-02-13 12:11

    Use BorderThickness="1,0,1,1" and a DataTrigger which checks for RelativeSource={RelativeSource Mode=PreviousData} being null to set BorderThickness="1,1,1,1":

    <Window x:Class="CollapseBordersDemo.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:sys="clr-namespace:System;assembly=mscorlib"
            Title="MainWindow" Height="239" Width="525">
      <Window.Resources>
        <x:Array x:Key="ListBoxItems" Type="{x:Type sys:String}">
          <sys:String>Alice</sys:String>
          <sys:String>Bob</sys:String>
          <sys:String>Colleen</sys:String>
        </x:Array>
        <DataTemplate x:Key="ListBoxTemplate">
          <Border x:Name="Border" BorderThickness="1,0,1,1" BorderBrush="DarkSlateGray" Background="LightGray" Padding="8 4 8 4">
            <TextBlock Text="{Binding}" FontSize="16"/>
          </Border>
          <DataTemplate.Triggers>
            <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=PreviousData}}" Value="{x:Null}">
              <Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,1"/>
            </DataTrigger>
          </DataTemplate.Triggers>
        </DataTemplate>
      </Window.Resources>
      <Grid>
        <ListBox ItemsSource="{StaticResource ListBoxItems}" ItemTemplate="{StaticResource ListBoxTemplate}" HorizontalContentAlignment="Stretch" />
      </Grid>
    </Window>
    
    0 讨论(0)
  • 2021-02-13 12:14

    You may add

     Margin="0,0,0,-1" SnapsToDevicePixels="True"
    

    to the border definition

    0 讨论(0)
提交回复
热议问题