0

I'm trying to do this XAML:

<UserControl.Resources>
    <Style TargetType="Label">
        <Setter Property="Foreground" Value="Blue"/>
    </Style>
</UserControl.Resources>

in C# code.

Here's my attempt in the UserControl Constructor:

InitializeComponent();

string labelForegroundColor = "Blue";

string labelXAMLStyle = @"<Style xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' TargetType=""Label"">
        <Setter Property=""Foreground"" Value=""{LabelForegroundColor}""/>
    </Style>";

labelXAMLStyle = labelXAMLStyle.Replace("{LabelForegroundColor}", labelForegroundColor);

StringReader mainLabelStyleXAMLStringReader = new StringReader(labelXAMLStyle);
XmlReader mainLabelStyleXAMLXMLReader = XmlReader.Create(mainLabelStyleXAMLStringReader);
Style mainLabelStyle = (Style)XamlReader.Load(mainLabelStyleXAMLXMLReader);

this.Resources.Add("LabelStyle", mainLabelStyle);

When I have the XAML in my UserControl it obviously works, but when I remove the XAML and add the code in my UserControl Constructor; it doesn't.

Where am I going wrong? Do I have to add some sort of Resource Dictionary?

How can I get it right to set the style of all Label's in my one specific UserControl?

Shiasu-sama
  • 1,179
  • 2
  • 12
  • 39
  • Did your tried this one already? https://stackoverflow.com/questions/3199424/how-to-set-the-style-programmatically – Ronald Haan May 02 '19 at 08:28
  • I can create the style in C# programmatically, but I don't know how to then set that style as the default style for all Labels in my UserControl. @RonaldHaan – Shiasu-sama May 02 '19 at 14:36

1 Answers1

1

You can try to create a style programatically and then add it to the resources.

    Style style = new Style(typeof(Label));
    style.Setters.Add(new Setter(Label.ForegroundProperty, Brushes.Blue));
    Resources[typeof(Label)] = gridStyle;