设置WPF按钮式编程方式
我有以下样式:设置WPF按钮式编程方式
<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只是添加背景颜色的旧式。但是这种新风格没有被应用。我仍然没有背景颜色的风格。
有人能帮我解决这个问题吗?
您的样式重写了按钮的ControlTemplate
,因此不再使用背景颜色。
在控件模板,背景属性添加到边境这样
<Border CornerRadius="0,0,4,4" BorderBrush="black" BorderThickness="1,0,1,1"
Background="{TemplateBinding Background}">
然后,它会使用你所设置的任何背景。
谢谢。这工作:) –
这可以在使用数据触发器的样式中没有代码的情况下完成。如果将数据触发器绑定到表示条件变化的属性,则使用触发器中的设置器进行更改。例如:
<Button>
<Button.Style>
<Style TargetType="Button">
<Setter Property="Background" Value="White"></Setter>
<Style.Triggers>
<DataTrigger Binding="{Binding condition}" Value="True">
<Setter Property="Background" Value="Black"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
这对我来说比你想要调整风格的方式更容易和更整齐。它将它全部保留在一个地方,而不是一半放在XAML中,一半放在代码后面。
嗨。我没有使用MVVM,因为它只是一个简单的1窗口项目,它从用户获取一些数据并通过WEB API更新某个表。我的意图是通过改变背景颜色,用户将对他选择的选项有一个视觉反馈。所以在点击按钮时,我试图改变背景颜色。而已。 –
不是一个问题,但是如果你在XAML中定义了新的样式,那么编写和读取比在代码后面更容易。 – kennyzx
我试着先在XAML中定义样式,然后像样式一样设置像这样的btn_bfx.Style = FindResource(“RoundCornerBackground”);它也没有工作。 –
这可以在使用数据触发器的样式中没有代码的情况下完成。如果将数据触发器绑定到表示条件变化的属性,则使用触发器中的设置器进行更改。 – kenjara