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?
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With