ListBox Foreground Color Problem for Selected Item Without ItemContainer

亡梦爱人 提交于 2020-01-16 18:41:48

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/1875152/listbox-foreground-color-problem-for-selected-item-without-itemcontainer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!