Question

alt text http://akashkava.com/blog/wp-content/uploads/2009/12/ListBoxItem-Selection-Problem.png

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.

Was it helpful?

Solution

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

alt logical tree http://img13.imageshack.us/img13/9082/logicaltree.jpg

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top