Define multiple styles for a Usercontrol via Staticresource’s in WPF

Asked

Viewed 117 times

1

I’m starting to work with WPF because of its resemblance to HTML. I realized through my research that when I use an expression like this Style="{StaticResource MeuStyle}" looks a lot like a class definition I have in html (class="MeuStyle").

Is it possible to merge several styles into a single Staticresource so that it is applied over the Style of that component? My intention is to work similar to bootstrap, where I set 2 classes on a button like this:

In HTML

<button class="btn">MeuButton</button>
<button class="btn btn-success">MeuButton</button>
<button class="btn btn-error">MeuButton</button>

In WPF ~ (what I need)

<Button Content="Button" Style="{StaticResource btn}"/>
<Button Content="Button" Style="{StaticResource btn, btnSuccess}"/>
<Button Content="Button" Style="{StaticResource btn, btnError}"/>
  • You don’t need to use the tag visual-studio when the problem has no relation to the IDE. If you have any questions about this, read this question

1 answer

1


Cannot specify more than one Resource using the StaticResource nor the DynamicResource, but what you can do, and which is also recommended, is to create a style and then create another one based on the first one through the property Style.BasedOn.

Take an example:

<Style x:Key="Style1">
  <Setter Property="Control.Background" Value="Yellow"/>
</Style>

<Style x:Key="Style2" BasedOn="{StaticResource Style1}">
  <Setter Property="Control.Foreground" Value="Blue"/>
</Style>

In the example above the Style2, if applied to an element, will apply the change of Control.Background of Style1 and the amendment of Control.Foreground of Style2 in itself, that way you get an inheritance-like effect and that seems to be what you seek.

  • That’s right partner, I published it some time ago and forgot rsrsrs, but it was worth the intention

Browser other questions tagged

You are not signed in. Login or sign up in order to post.