我有以下风格(为了简洁起见),并有一些基于它的问题。据我所知,如果ControlTemplate替换了样式所基于的控件的整个视觉树,那么属性Setter会有什么影响呢?
在本例中,FontSize、Margin、Height等的属性Setter不是对应于CheckBox本身的相应属性吗?如果替换控件的Template属性,那么如果CheckBox不再呈现其默认外观,这些Setter将对应于什么?
<Style x:Key="KeyName" TargetType="CheckBox">
<Setter Property="FontSize" Value="11" />
<Setter Property="Margin" Value="0 0 1 0" />
<Setter Property="VerticalAlignment" Value="Top" />
<Setter Property="Height" Value="18" />
... common property setters etc.
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="CheckBox">
<Border>
<StackPanel>
<Ellipse Name="Ellipse" Width="7" Height="7" />
<ContentPresenter Content="{TemplateBinding Content}" />
</StackPanel>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Trigger.Setters>
<Setter Property="Foreground" Value="WhiteSmoke" />
</Trigger.Setters>
</Trigger>
... custom triggers etc ...
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>发布于 2012-11-07 00:43:35
它们是为正在设置样式的对象上的属性提供初始默认值的一种方法,它们不会自动强制模板上的任何内容。但是,它们可以在控件模板中使用。
使用样式中的setter设置的值可以由xaml中的本地值重写。例如。
这个xaml文件绘制了一个单独的标签,它的样式已更改为包含一个采用背景颜色的网格,我在setter中默认为红色,它显示为红色。
<Window x:Class="ContextMenu.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style TargetType="{x:Type Label}">
<Setter Property="Background" Value="Red"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Label}">
<Grid Background="{TemplateBinding Background}">
<TextBlock Text="{TemplateBinding Content}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Label>Test</Label>
</Window>如果我将label的实例上的标签行改为蓝色,您可以看到这会覆盖setter。
<Window x:Class="ContextMenu.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style TargetType="{x:Type Label}">
<Setter Property="Background" Value="Red"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Label}">
<Grid Background="{TemplateBinding Background}">
<TextBlock Text="{TemplateBinding Content}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Label Background="Blue">Test</Label>
</Window>https://stackoverflow.com/questions/13255406
复制相似问题