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?

2 Answers 2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.