views:

206

answers:

2

I still didn't get it. Could you please show me exactly how to override ListBox's default behavior. Everytime when ListBoxItem is selected the Border's background should be changed. Not the background of the whole row but only background of the border which's specified.

 <ListBox ItemsSource="{Binding Source={StaticResource AssetsViewSource}}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Border BorderThickness="2" BorderBrush="Black">
                    <StackPanel>
                        <TextBlock Text="Name: " />
                        <TextBlock Text="{Binding Name}" />
                    </StackPanel>
                </Border>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
+3  A: 

Use the DataTemplate's Triggers collection, with a RelativeSource to get you to the containing ListBoxItem:

<DataTemplate>
  <Border BorderThickness="2" BorderBrush="Black" Name="Bd">
    <StackPanel>
      <TextBlock Text="Name: " />
      <TextBlock Text="{Binding Name}" />
    </StackPanel>
  </Border>
  <DataTemplate.Triggers>
    <DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}"
                 Value="True">
      <Setter TargetName="Bd" Property="Background" Value="HotPink">  <!-- everybody loves HotPink -->
    </DataTrigger>
  </DataTemplate.Triggers>
</DataTemplate>
itowlson
Yeah it worked... but It didn't get rid of the default blue background.. How to do it?
Ike
Oh, I figured that out. I just put the copy of the default <ListBox.ItemContainerStyle> and cut all the triggers off.But I'm not sure this is the best way to do it...
Ike
When you say the "default" blue background, you mean the automatic selection colour background of the whole row? If so, you're doing it right: ItemContainerStyle is the only way to get rid of that. Apologies for not covering this in the original answer -- I misunderstood when you said "Not the background of the whole row" and thought you wanted to leave the automatic selection colour there.
itowlson
+1  A: 

Simply add the following into the ListBox Item tag

<ListBox.Resource>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
</ListBox.Resource>

That should do the trick..

mkazanova
I don't have time to check that right now, still consider that as a correct answer and solution. Thank you.
Ike