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?

Community
  • 1
  • 1
Gigi
  • 28,163
  • 29
  • 106
  • 188

2 Answers2

15

As an alternative, you can try this:

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);
}
Anatoliy Nikolaev
  • 22,370
  • 15
  • 69
  • 68
8

This is a workaround that works. Add a style based on ToolBar.ButtonStyleKey to Window.Resources as follows:

<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.

Gigi
  • 28,163
  • 29
  • 106
  • 188