开发者

ListBox Foreground Color Problem for Selected Item Without ItemContainer

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

The following code, behaves little strange.

<ListBox SelectionMode="Multiple">

        &l开发者_Go百科t;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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜