以编程方式设置按钮平面样式

Gig*_*igi 7 c# wpf styles

当某些条件发生时,我想以编程方式给按钮一个平面样式.

这个问题展示了我如何以编程方式为控件设置样式,已经在XAML中定义了它.

此问题表明已存在平面按钮样式,因此无需在XAML中创建一个.

ToolBar.ButtonStyleKey返回一个ResourceKey,并且我的窗口中没有定义相应的样式(它在ToolBar中).如何在代码中使用它来以编程方式设置样式?

Ana*_*aev 15

作为替代方案,您可以尝试这样做:

XAML

<Button Name="FlatButton" Width="100" Height="30" Content="Test" />
Run Code Online (Sandbox Code Playgroud)

Code behind

private void Button_Click(object sender, RoutedEventArgs e)
{
    FlatButton.Style = (Style)FindResource(ToolBar.ButtonStyleKey);
}
Run Code Online (Sandbox Code Playgroud)


Gig*_*igi 8

这是一种有效的解决方法.添加基于一种风格ToolBar.ButtonStyleKey,以Window.Resources如下:

<Window.Resources>
    <Style x:Key="MyStyle" BasedOn="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" TargetType="Button" />
</Window.Resources>
Run Code Online (Sandbox Code Playgroud)

然后,在代码中,根据此问题中的第一个链接引用它:

button.Style = this.Resources["MyStyle"] as Style;
Run Code Online (Sandbox Code Playgroud)

我更喜欢有一个仅代码解决方案(没有XAML),但这也适用.