本文介绍了对于所选项,而不ItemContainer列表框前景色问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面code,行为有些奇怪。

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>

需要注意的是第一个选择停留在黑色,就是因为项目不是自己的ItemContainer,但在第2项的情况下是自己的ItemContainer所以风格正常工作。时间多数我们填充数据,通过模板,每次我们的项目不是自己的ItemContainer而这就是为什么TextBlock的行为怪相对于前景色。

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.

重要提示:我在寻找的答案,为什么出现这种情况并不怎么解决呢,我知道了解决方法TextElement.Foreground ={TemplateBinding前景},但我想知道为什么会这样。

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:

在明确指定一个ListBoxItem将其添加到逻辑树,前景是从它继承。一旦和StackPanel中,逻辑树是不同的,前景是从不同的父文件夹继承。我敢肯定,你以前读过这一点,但只是为了记录。有一个从迈克Hillberg真正伟大的文章:的逻辑和视觉树。他解释这种行为很清楚。

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.

干杯

这篇关于对于所选项,而不ItemContainer列表框前景色问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 02:45