Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the selected text color in a TextBlock in a ListView?

I am building a Windows 8 store application and I can't manage to change the highlighted/selected color a of TextBlock in a ListView.

Here's how I create my ListView :

<ListView x:Name="zonesList" HorizontalAlignment="Left" Height="516" Margin="50,175,0,0" ItemTemplate="{StaticResource LocalizationCellSample}" VerticalAlignment="Top" Width="355" DataContext="{Binding}" SelectionChanged="zonesList_SelectionChanged"/>

And my data binding:

<DataTemplate x:Key="LocalizationCellSample">
  <Grid HorizontalAlignment="Left">
    <TextBlock Style="{StaticResource ListBoxTextStyle}" TextWrapping="Wrap" Width="200" MaxHeight="20" VerticalAlignment="Center" Text="{Binding name}" HorizontalAlignment="Left" Margin="20,5,0,0" FontFamily="Global User Interface"/>
  </Grid>
</DataTemplate>

What's the easiest way?

EDIT:

Here's the ListBoxTextStyle

<Style x:Key="ListBoxTextStyle" TargetType="TextBlock">
  <Setter Property="FontFamily" Value="Segoe UI Light" />
  <Setter Property="FontSize" Value="16" />
</Style>
like image 330
Antoine Gamond Avatar asked Nov 24 '22 03:11

Antoine Gamond


1 Answers

Add ItemContainerStyle to the ListView

Add the ItemContainerStyle like the picture shows in the "DocumentOutline" Panel in Visual Studio. Then Edit the VisualState as below:

<VisualState x:Name="Selected">
    <Storyboard>
        <ColorAnimation Duration="0" To="Red" Storyboard.TargetProperty="(ContentPresenter.Foreground).(SolidColorBrush.Color)"
                        Storyboard.TargetName="contentPresenter" />
    </Storyboard>
</VisualState>
<VisualState x:Name="SelectedUnfocused">
    <Storyboard>
        <ColorAnimation Duration="0" To="Red" Storyboard.TargetProperty="(ContentPresenter.Foreground).(SolidColorBrush.Color)" 
                        Storyboard.TargetName="contentPresenter" />
    </Storyboard>
</VisualState>

Usually, the "contentPresenter" is added to the ItemContainerStyle by default. The Foreground of the "contentPresenter" changes, the Color of Text will change.

As for the Background of the selected ListViewItem, nearly the same as above.

By the way, It works in WP8.1, at least. And if you do it in Blend, it will be easier.

like image 150
Silenco Tang Avatar answered Jan 28 '23 13:01

Silenco Tang