views:

196

answers:

1

alt text

The following code, behaves little strange.

<ListBox SelectionMode="Multiple">

     <StackPanel>
      <TextBlock>Selection is Black</TextBlock>
     </StackPanel>

     <ListBoxItem>
      <StackPanel>
       <TextBlock>Selection is White</TextBlock>
      </StackPanel>
     </ListBoxItem>
</ListBox>

Note that first selection stays in black color, that is because the Item is not its own ItemContainer, however in 2nd case Item is its own ItemContainer so the style works correctly. Majority of time we populate data through templates and everytime our Item is not its own ItemContainer and thats why TextBlock behaves strange with respect to foreground color.

Important: I am looking for the answer to "Why this happens" not how to solve it, I know the workaround TextElement.Foreground="{TemplateBinding Foreground}", but I want to know why this is happening.

+2  A: 

Hi Akash,

I guess, that's because the logical trees are different here:

alt logical tree

When you explicitly specify ListBoxItem you add it to the logical tree, and Foreground is inherited from it. In case with StackPanel, logical tree is different, and Foreground is inherited from different parent... I'm sure you've read this before, but just for the log. There is really great article from Mike Hillberg: Of logical and visual trees in WPF. He explains this behavior very clearly.

Cheers

Anvaka
Thanks for the answer, can you tell me where and how I can see this logical tree?? which tool did you use to find this out? But I doubt this is the case because "Styles" and templates are supposed to work for visual trees correctly.
Akash Kava
The tool is Mole: http://karlshifflett.wordpress.com/mole-for-visual-studio/
Anvaka
Thanks for your answer, I read in detail that DPs actually follow logical parent first and then visual.. this certainly is a problem in case of itemscontrol, i reported to microsoft but they will just say "Resolved by Design" however it just means that i have to rewrite lot of library code in order to make this work.
Akash Kava