7

I want to give a button a flat style programmatically when certain conditions occur.

This question shows how I can set a style to a control programmatically, having already defined it in XAML.

This question shows that a flat button style already exists, so it is not necessary to create one in XAML.

ToolBar.ButtonStyleKey returns 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?

4

2 回答 2

15

作为替代方案,您可以尝试以下操作:

XAML

<Button Name="FlatButton" Width="100" Height="30" Content="Test" />

Code behind

private void Button_Click(object sender, RoutedEventArgs e)
{
    FlatButton.Style = (Style)FindResource(ToolBar.ButtonStyleKey);
}
于 2013-09-08T10:40:02.393 回答
8

这是一种有效的解决方法。添加基于ToolBar.ButtonStyleKeyto的样式Window.Resources,如下所示:

<Window.Resources>
    <Style x:Key="MyStyle" BasedOn="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" TargetType="Button" />
</Window.Resources>

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

button.Style = this.Resources["MyStyle"] as Style;

我更愿意为此提供一个纯代码解决方案(无 XAML),但这也同样有效。

于 2013-09-08T10:30:51.557 回答