WPF Style to all control of the same type in one UserControl

Aug 25, 2009 at 5:23 PM
Edited Aug 25, 2009 at 6:33 PM

Hello,
Is there a way to apply a style to all controls of the same type in one user control dynamically, without applying in all controls of my application and without go to the control and set the style manually?

The problem is that in my ResorceDictionary I have 2 styles, with the x:Key set

<Style x:Key="ScrollBar_White" TargetType="{x:Type ScrollBar}">
<Style x:Key="ScrollBar_Black" TargetType="{x:Type ScrollBar}">

And I want to know if there is a way in XAML to apply dynamically a named style without use the following code on all the scrollbars of my UserControl.

<ScrollBar Style="ScrollBar_White">


Coordinator
Aug 25, 2009 at 9:42 PM
Edited Aug 25, 2009 at 9:43 PM

Hi Crasiness,

You will want to use BasedOn to apply your application-wide style to particular UserControls.  If you include the markup you have above in your main resource dictionary and add the following to your UserControl dictionary:

<Style BasedOn="{StaticResource ScrollBar_White}" TargetType="{x:Type ScrollBar}" />

you will apply the ScrollBar_White style to all of the ScrollBars in the UserControl only.  You also won't need to specify this style per-control (i.e. for each ScrollBar) to get this behavior once it's specified for the general UserControl. 

Hope that helps!

Alexis

Aug 25, 2009 at 10:16 PM
Edited Aug 25, 2009 at 10:52 PM

Hello Alexis,

Thanks for your reply, this solution actually works if the styles are StaticResource but I have another problem, the styles are DynamicResource and with that I cannot use the BasedOn.

Another idea?

Many thanks ,
Paulo