-2

I have created a custom control that serves as the basis for a few others I'm making. I've then defined control templates for each one, so now I can do the following:

<!-- First layout -->
<custom:MyCustomControl Style="{StaticResource CustomStyle1}" />
<!-- Second layout -->
<custom:MyCustomControl Style="{StaticResource CustomStyle2}" />
...
etc.

I then wanted to make it so I could switch from one style to another with the press of a button. My initial idea to do this was to create custom Button with a StyleToApply dependency property and a way to find its containing parent. I would then set the button's OnClick method to change the style of its containing control's to that of the button's dependency property. However, my styles don't get recognised:

<!-- Within a custom control or user control -->
<local:StyleButton StyleToApply="{StaticResource ResourceKey}" ... />
                                                      ^ no suggested styles

Is it even possible to achieve this? If so, how? If not, what could I do instead?

JansthcirlU
  • 688
  • 5
  • 21

1 Answers1

0

One possible solution for this would be to have both controls in your XAML and bind their Visibility to a property in your viewmodel i.e. bind Control1's Visibility to public bool StandardLayout in your viewmodel, and Control2's Visibility to the inverse of that.

Idea from this answer and enhancement by me:

<Window.Resources>
    <BooleanToVisibilityConverter x:Key="BooleanToVisibility" />
</Window.Resources>

<!-- First layout -->
<custom:MyCustomControl Style="{StaticResource CustomStyle1}" Visibility="{Binding StandardLayout, Converter={StaticResource BooleanToVisibility}}" />
<!-- Second layout -->
<custom:MyCustomControl Style="{StaticResource CustomStyle2}" Visibility="{Binding StandardLayout, Converter={StaticResource BooleanToVisibility}, ConverterParameter=Inverted}"/>

Disclaimer: I haven't tried the ConverterParameter=Inverted part myself yet, you might have to either make another viewmodel property that inverts the first, or an InverseBooleanToVisibilityConverter like in here.

Edit: Then the button, when clicked, would just flip the bool around and the controls switch visibilities.

Squirrelkiller
  • 2,575
  • 1
  • 22
  • 41