wpf 以编程方式设置按钮平面样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18682559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting button flat style programmatically
提问by Gigi
I want to give a button a flat style programmatically when certain conditions occur.
我想在某些条件发生时以编程方式为按钮提供平面样式。
This questionshows how I can set a style to a control programmatically, having already defined it in XAML.
这个问题显示了我如何以编程方式为控件设置样式,已经在 XAML 中定义了它。
This questionshows that a flat button style already exists, so it is not necessary to create one in XAML.
这个问题说明平面按钮样式已经存在,所以没有必要在XAML中创建一个。
ToolBar.ButtonStyleKeyreturns a ResourceKey, and the corresponding style is not defined in my window (it's in ToolBar). How do I use it in code to set the style programmatically?
ToolBar.ButtonStyleKey返回 a ResourceKey,并且我的窗口中没有定义相应的样式(它在工具栏中)。如何在代码中使用它以编程方式设置样式?
回答by Anatoliy Nikolaev
As an alternative, you can try this:
作为替代方案,您可以尝试以下操作:
XAML
XAML
<Button Name="FlatButton" Width="100" Height="30" Content="Test" />
Code behind
Code behind
private void Button_Click(object sender, RoutedEventArgs e)
{
FlatButton.Style = (Style)FindResource(ToolBar.ButtonStyleKey);
}
回答by Gigi
This is a workaround that works. Add a style based on ToolBar.ButtonStyleKeyto Window.Resourcesas follows:
这是一种有效的解决方法。添加基于ToolBar.ButtonStyleKeyto的样式Window.Resources如下:
<Window.Resources>
<Style x:Key="MyStyle" BasedOn="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" TargetType="Button" />
</Window.Resources>
Then, in code, refer to it as per first link in this question:
然后,在代码中,按照本问题中的第一个链接引用它:
button.Style = this.Resources["MyStyle"] as Style;
I'd prefer to have a code-only solution (no XAML) for this, but this works just as well.
我更愿意为此提供一个纯代码解决方案(无 XAML),但这也同样有效。

