i got a DataTemplate for a listboxitem and i want to create a triger , so when a user click an item the background will change and also the label
my code:
<Window.Resources>
<Style x:Key="RoundedItem" TargetType="ListBoxItem">
<EventSetter Event="MouseDoubleClick" Handler="listViewItem_MouseDoubleClick" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border Name="ItemBorder" CornerRadius="10" BorderBrush="Black" BorderThickness="1" Margin="1" Background="Transparent">
<Label Name="ItemLabel" Foreground="Red" >
<ContentPresenter />
</Label>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="ItemBorder" Property="Background" Value="DeepSkyBlue" />
<Setter TargetName="ItemLabel" Property="Foreground" Value="Orange" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<DataTemplate x:Key="TitleTemplate" DataType="models:Title" >
<StackPanel>
<Image Source="{Binding ThumbFilePath}" Width="50" HorizontalAlignment="Center"/>
<Label Content="{Binding Name}" HorizontalAlignment="Center" />
<TextBlock Text="{Binding Description}" HorizontalAlignment="Center" TextWrapping="Wrap" Padding="5,5,5,5"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
What happend is that the TextBlock change his color and not the label..
anyone know why ?
Thanks.
The
TextBlockinherits the Foreground definition from its parents in the visual tree. TheLabel, on the other hand, defines the Foreground in its default style.Your approach is “non-WPF-like” – you shouldn’t wrap the
ContentPresenterin aLabelcontrol.The right approach depends on whether you want all text in the item to change its Foreground, or just the label?
[In both cases, there’s no apparent benefit to using a
Labelin the data template – so I’ll assume that the label is changed toTextBlock.]If the answer to the above question is that all text should be changed: in the
ControlTemplateof theListBoxItem, in the trigger for IsSelected, from the seccond setter removeTargetName="ItemLabel"so the final setter is:This will change the foreground of the item that will affect the foreground of both
TextBlocks in the data template.If you want to affect just one of the TextBlocks:
Side note: if you have to use
Labelcontrol in your data template, bind its Foreground property to the Foreground of the list box item, like so:If this doesn’t help, it means that your list box item inherits its foreground, so use: