【发布时间】:2018-05-08 07:42:15
【问题描述】:
我的样式适用于我的应用程序的所有按钮:
<Style TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Background" Value="Red" />
<Setter Property="Foreground" Value="Black" />
<Setter Property="FontSize" Value="16" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid>
<Ellipse x:Name="StatusButtonCircle" Stroke="Black" StrokeThickness="0" Fill="AliceBlue" Stretch="Uniform">
<Ellipse.Width>
<Binding ElementName="StatusButtonCircle" Path="ActualHeight"/>
</Ellipse.Width>
</Ellipse>
<Ellipse x:Name="StatusButtonCircleHighlight" Margin="4" Stroke="Black" StrokeThickness="2" Stretch="Uniform">
<Ellipse.Width>
<Binding ElementName="StatusButtonCircleHighlight" Path="ActualHeight"/>
</Ellipse.Width>
</Ellipse>
<ContentPresenter HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
<ControlTemplate.Triggers>
... some Triggers here
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
如何更改 XAML 中的属性(例如 FontWeight、FontSize 等)?我试过这个:
<Button FontWeight="Bold" FontSize="30" Foreground="Red">
</Button>
在设计器视图中,我看到了变化。但在运行时这些更改不会应用。
经过一番调查,我也有一个适合所有 TextBlock 的样式,如下所示:
<Style TargetType="{x:Type TextBlock}">
<Setter Property="FontSize" Value="16" />
<Setter Property="FontFamily" Value="Segoe UI Semibold" />
<Setter Property="Foreground" Value="White" />
</Style>
此样式似乎覆盖了按钮上使用的 TextBlock。我仍然无法更改 XAML 中的文本属性。
如果我在一个空项目中使用上述样式,效果如下:
在设计器中应用更改,在运行时应用来自 TextBlock 的更改。如果我为 TextBlock 分配一个 x:Key,它就可以正常工作。但是我必须手动将此样式分配给应用程序中使用的每个 TextBlock。
【问题讨论】:
-
您提供的代码不会重现该问题。我刚刚创建了新项目,将 Button 和 TextBlock 样式添加到资源中,添加了 Button 元素,并且它可以工作(前景为红色)。尝试创建一个可以重现问题的测试项目。
-
BasedOn 应该指向另一个Button的“base”样式,它不用于指定目标类型。
-
@Fredrik 当你想扩展类型的全局样式时可以这样使用 - microsoft docs。
-
@djomlastic 是的。谢谢。
标签: wpf xaml button properties