tags:

views:

24

answers:

1

I have a collection of items. I am presenting the items in a WPF ListBox using DataTemplate. Part of the DataTemplate is a Thumb which is used for resizing and visually separating between items. The Thumb.Visibility is binded to a property of the item (for example, the last item doesn’t have a visible Thumb).

The problem is that selecting an item in the ListBox selects the Thumb as well, as it is part of the ListBoxItem. The desired behavior is to select only the data without the Thumb.
How is it possible to get this behavior? I don’t want to add items by code the ListBox or to handle the visibility of the Thumb manually. Currently I get all this from the DataTemplate.

A: 

Do this inside item container style, not DataTemplate. I.e. define your own ListBoxItem style and highlight only what's required. E.g.:

<Style x:Key="MyStyle" TargetType="{x:Type ListBoxItem}">
  <Setter Property="SnapsToDevicePixels" Value="true"/>
  <Setter Property="OverridesDefaultStyle" Value="true"/>
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type ListBoxItem}">
       <Grid>
        <Border 
          Name="Border"
          Margin="0, 0, 0, 1"
          Padding="2"
          SnapsToDevicePixels="true">
          <ContentPresenter />
        </Border>
         <Border Grid.Row="1" BorderThickness="0, 0, 0, 1" BorderBrush="Black"
                 SnapsToDevicePixels="True"/>
        </Grid>
        <ControlTemplate.Triggers>
          <Trigger Property="IsSelected" Value="true">
            <Setter TargetName="Border" Property="Background" Value="#DDDDDD"/>
          </Trigger>
          <Trigger Property="IsEnabled" Value="false">
            <Setter Property="Foreground" Value="#888888"/>
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

And then:

<ListBox ItemContainerStyle="{StaticResource MyStyle}">
Anvaka