Mark Carpenter
Mark Carpenter

Reputation: 17775

Can I dynamically switch between styles in WPF?

Let's say I wanted to display a Button and a few RadioButtons. Based on which RadioButton is selected, I want to apply a different style to my Button. Is this possible in WPF?

Upvotes: 1

Views: 7370

Answers (2)

Mark Carpenter
Mark Carpenter

Reputation: 17775

@Brandon's answer would have worked, but I think this is a little more elegant:

<ComboBox Name="AvailableStyles">
    <ComboBoxItem Tag="{x:Null}" IsSelected="True">None</ComboBoxItem>
    <ComboBoxItem Tag="{StaticResource FirstStyle}" Style="{StaticResource FirstStyle}">Style 1</ComboBoxItem>
    <ComboBoxItem Tag="{StaticResource SecondStyle}" Style="{StaticResource SecondStyle}">Style 2</ComboBoxItem>
    <ComboBoxItem Tag="{StaticResource ThirdStyle}" Style="{StaticResource ThirdStyle}">Style 3</ComboBoxItem>
</ComboBox>

<Button Style="{Binding ElementName=AvailableStyles, Path=SelectedItem.Tag}"  Content="Dynamically Styled Button" />

Upvotes: 12

Brandon
Brandon

Reputation: 70022

You can just set the Style in the code behind.

    button.Style = (Style)FindResource("NameOfYourStyle");

Upvotes: 8

Related Questions