Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting button flat style programmatically

Tags:

c#

styles

wpf

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?

like image 715
Gigi Avatar asked Sep 08 '13 10:09

Gigi


2 Answers

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);
}
like image 78
Anatoliy Nikolaev Avatar answered Oct 01 '22 04:10

Anatoliy Nikolaev


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.

like image 36
Gigi Avatar answered Oct 01 '22 03:10

Gigi