WPF style for managing one UserControl

Is there a way to apply a style for all controls of the same type in a user element, one dynamically, without applying to all the controls in my application and without going into the control and setting the style manually

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

<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 a dynamically named style without using the following code on all scrollbars of my UserControl.

<ScrollBar Style="ScrollBar_White">

EDIT

Sorry, I'm new to WPF, so I don’t have enough for you to know what is important (what I discovered after applying your last solution). The latter solution really works if the styles are StaticResources, but they are DynamicResources, and BasedOn do not work with DynamicResources.

Any idea how to do this with DynamicResource?

Thank you very much and it is a pity that I missed important questions in my questions.

+3
source share
1 answer

Yes, add it to the resource dictionary of the corresponding control.

"", , , XAML. ResourceDictionary.Add .

:

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);
}

( XAML):

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

x:Key, . ( ).

, , :

<!-- 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>
+8

Source: https://habr.com/ru/post/1716011/


All Articles