This is a mirror of official site: http://jasper-net.blogspot.com/

Accent Colors for Styled TextBlocks in WP7 Selected ListBoxItems

| Monday, November 15, 2010
The Problem

The Windows Phone tools in Visual Studio an Expression Blend let you create a 'Windows Phone Data Bound Application" (Template). This application uses SampleData and two List/Detail pages. The List (MainPage) contains a listbox which is templated. The ItemSource of this listbox is databound to the Items in the SampleData. When run the application and select an Item in the ListBox the DetailsPage is shown using navigation. This navigation is initiated from the SelectionChanged event of the listbox in the MainPage. When you remove this event from the XAML you would expect that the selected item in the listbox would be shown using the Accent color of your phone. But this doesn't happen. It took me a while to figure out the reason why, and how to solve it.

<ListBox x:Name="MainListBox"
           Margin="0,0,-12,0"
           ItemsSource="{Binding Items}">
   <ListBox.ItemTemplate>
       <DataTemplate>
           <StackPanel Margin="0,0,0,17"
                       Width="432">
               <TextBlock Text="{Binding LineOne}"
                           TextWrapping="Wrap"
                           Style="{StaticResource PhoneTextExtraLargeStyle}" />
               <TextBlock Text="{Binding LineTwo}"
                           TextWrapping="Wrap"
                           Margin="12,-6,12,0"
                           Style="{StaticResource PhoneTextSubtleStyle}" />
           </StackPanel>
       </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

The Reason

The Selected (Visual)State of a ListBoxItem sets the foreground of the ContainerControl to the PhoneAccentBrush resource. The Two TextBlockes in the ItemTemplete of my listbox have a Style Property. Both styles are base on the PhoneTextBlockBase which has a Foreground property set to the PhoneForegroundBrush resource. This conflicts with the foreground set in the VisualState and therefore the color never changes.

Read more: Reflection It

Posted via email from .NET Info

0 comments: