这个问题的灵感来自 this recent question以及我在 WPF 开发中遇到的其他情况。我如何知道在控件上设置样式以覆盖某些默认行为与创建新的控件模板是否足够?
更具体地说,在上面的问题中,作者想要在选择 ListBoxItem 时更改它的外观。 (见下面转载的代码)。一切正常,但 Background 属性除外。人们怎么知道他们应该为此覆盖控制模板?
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Content" Value="{Binding Path=Name}"/>
<Setter Property="Margin" Value="2"/>
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="FontSize" Value="18"/>
<Setter Property="Background" Value="Yellow"/>
<Setter Property="Foreground" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
最佳答案
关于是使用样式还是模板,Ray 给出了很好的回答。
至于如何在不创建模板的情况下解决您的问题,也许我可以提供帮助。
背景颜色由 SystemColors 设置。使用 Blend 并创建一个模板,您可以看到确切的 xaml。
所以如果没有模板!是一项要求,您可以随时更改该资源的内容。
示例:
<ListBox>
<ListBox.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="Yellow" />
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Content" Value="{Binding Path=Name}"/>
<Setter Property="Margin" Value="2"/>
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="FontSize" Value="18"/>
<Setter Property="Foreground" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
</ListBox.Resources>
<ListBoxItem>Test 1</ListBoxItem>
<ListBoxItem>Test 2</ListBoxItem>
<ListBoxItem>Test 3</ListBoxItem>
</ListBox>
这将为您提供给定 ListBox 的背景颜色,而不会搞砸应用程序中的任何其他内容。
关于c# - 我如何知道是使用样式还是覆盖控件模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/491739/