【发布时间】:2017-05-08 09:50:51
【问题描述】:
我有以下风格:
<Window.Resources>
<Style x:Key="RoundCorner" TargetType="{x:Type Button}">
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Padding" Value="1"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border CornerRadius="0,0,4,4" BorderBrush="black"
BorderThickness="1,0,1,1" >
<ContentPresenter HorizontalAlignment="Center"
VerticalAlignment="Center"
Margin="1"></ContentPresenter>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="LayoutTransform">
<Setter.Value>
<RotateTransform CenterX="0.5" CenterY="0.5" Angle="270" />
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
我将它设置为这样的按钮
<Button x:Name="btn_bfx" ToolTip="BreakFix" Content="BFX" Click="btn_bfx_Click" Height="30" Width="40" HorizontalContentAlignment="Center" ></Button>
在构造函数中,我将样式设置为:
btn_bfx.Style = this.Resources["RoundCorner"] as Style;
稍后根据某些情况我想更改样式。
代码如下:
Style oldStyle = FindResource("RoundCorner") as Style;
Style newStyle = new Style();
newStyle.BasedOn = oldStyle;
newStyle.TargetType = typeof(Button);
foreach (var setter in oldStyle.Setters.ToList())
{
newStyle.Setters.Add(setter);
}
newStyle.Setters.Add(new Setter(BackgroundProperty, Brushes.CadetBlue));
btn_bfx.Style = newStyle;
newStyle 只是为 oldStyle 添加背景颜色。但这种新风格并没有被应用。我仍然得到没有背景颜色的样式。
【问题讨论】:
-
不是一个答案,但如果你也在 XAML 中定义新样式,它会比在后面的代码中更容易编写和阅读。
-
我尝试先在 XAML 中定义样式,然后像这样设置 btn_bfx.Style = FindResource("RoundCornerBackground") as Style;它也没有工作。
-
这可以在样式中使用数据触发器在没有代码的情况下完成。如果您将数据触发器绑定到表示您的条件更改的属性,则使用触发器中的设置器进行更改。
标签: wpf xaml resourcedictionary