wpf 如何在 ComboBox 中设置 ContentPresenter 的样式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20121319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to style ContentPresenter in ComboBox?
提问by Spook
I'm currently styling ComboBoxto look like one in Visual Studio (along with color theme). I've done most of the styling, but stopped at the ContentPresenterdisplaying the currently chosen object.
我目前的样式ComboBox看起来像 Visual Studio 中的样式(以及颜色主题)。我已经完成了大部分样式,但在ContentPresenter显示当前选择的对象时停了下来。
The piece of XAML looks like the following:
这段 XAML 如下所示:
<ContentPresenter Margin="2" IsHitTestVisible="False" VerticalAlignment="Center" HorizontalAlignment="Stretch"
Name="ContentSite"
ContentTemplate="{TemplateBinding ComboBox.SelectionBoxItemTemplate}"
Content="{TemplateBinding ComboBox.SelectionBoxItem}" />
The problem is, that the default SelectionBoxItemTemplateseems to ignore ComboBox's Foreground value:
问题是,默认SelectionBoxItemTemplate似乎忽略了 ComboBox 的 Foreground 值:
<ComboBox Margin="4" SelectedIndex="0" Foreground="Red">
<ComboBoxItem>First</ComboBoxItem>
<ComboBoxItem>Second</ComboBoxItem>
<ComboBoxItem>Third</ComboBoxItem>
</ComboBox>


The first one is non-editable, SelectionBoxItemTemplatekicks in and forces set the color of the text to black (even though Foregroundis set manually to red and in style to another non-black color).
第一个是不可编辑的,SelectionBoxItemTemplate启动并强制将文本的颜色设置为黑色(即使Foreground手动设置为红色并在样式中设置为另一种非黑色)。
How can I pass the current foreground color to the ContentPresenter? If I can't, where can I find working replacement for the SelectionBoxItemTemplate? (working, in terms, that it'll work correctly for all item types in the ComboBox)
如何将当前的前景色传递给ContentPresenter? 如果我不能,我在哪里可以找到工作的替代品SelectionBoxItemTemplate?(工作,就其而言,它将适用于 中的所有项目类型ComboBox)
回答by Sheridan
I don't think that it does ignore the Foregroundcolour. If you add a (normal) ComboBoxcontrol like the following to your XAML...:
我不认为它确实忽略了Foreground颜色。如果ComboBox向 XAML添加如下所示的(普通)控件...:
<ComboBox Foreground="Red">
<ComboBoxItem>One</ComboBoxItem>
<ComboBoxItem>Two</ComboBoxItem>
<ComboBoxItem>Three</ComboBoxItem>
<ComboBoxItem>Four</ComboBoxItem>
</ComboBox>
... you will see that setting the Foregrounddoeschange the selected item text. I think that perhaps your problem lies in yourControlTemplate. Now I can't be 100% sure, but I would have thought that your ContentPresentershould look like this instead:
...您将看到设置Foreground确实会更改所选项目的文本。我想也许你的问题出在你的ControlTemplate. 现在我不能 100% 确定,但我认为你ContentPresenter应该看起来像这样:
<ContentPresenter Margin="2" IsHitTestVisible="False" VerticalAlignment="Center"
HorizontalAlignment="Stretch" Name="ContentSite" ContentTemplate="{TemplateBinding
SelectionBoxItemTemplate}" Content="{TemplateBinding SelectionBoxItem}" />

