tags:

views:

792

answers:

1

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?

EDIT 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">

EDIT

I'm sorry, I'm new at WPF, so I'm missing to let you know somethings that are important (that I discover after applying your last solution). The last solution actually works if the styles are StaticResources, but they are DynamicResources and the BasedOn don't work well with DynamicResources.

Any Idea how to do this with DynamicResource?

Many thanks, and sorry I miss important points in my questions.

+1  A: 

Yes, add it to the resource dictionary of the control in question.

When you say 'dynamically', I assume you mean in code rather than in XAML. You could use the ResourceDictionary.Add method on your user control from the code-behind.

Here's some sample code:

public MyUserControl()
{
    InitialiseComponent();

    var style = new Style(typeof(TextBlock));
    var redBrush = new SolidColorBrush(Colors.Red);
    style.Setters.Add(new Setter(TextBlock.ForegroundProperty, redBrush));
    Resources.Add(typeof(TextBlock), style);
}

This is the equivalent of (in XAML):

<UserControl.Resources>
  <Style TargetType="TextBlock">
    <Setter Property="Foreground" Value="Red" />
  </Style>
</UserControl.Resources>

Because no x:Key is applied to the style, it is picked up by all instance of the target type. Internally, the type itself is used as a key (I believe).

EDIT

Given the update to your question, it seems that you want this:

<!-- this is the parent, within which 'ScrollBar_White' will be applied
     to all instances of 'ScrollBar' -->
<StackPanel>
  <StackPanel.Resources>
    <Style TargetType="ScrollBar" BasedOn="{StaticResource ScrollBar_White}" />
  </StackPanel.Resources>
  <!-- scrollbars in here will be given the 'ScrollBar_White' style -->
<StackPanel>
Drew Noakes