Search code examples
c#wpfwpf-style

How to add a Style to UserControl Resources in C# programmatically?


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?


Solution

  • 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;