如何以编程方式向 C# 中的 UserControl 资源添加样式?

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

我正在尝试这样做 XAML:

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

在 C# 代码中。

这是我在 UserControl 构造函数中的尝试:

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

当我的 UserControl 中有 XAML 时,它显然有效,但是当我删除 XAML 并在我的 UserControl 构造函数中添加代码时;它没有。

我哪里错了? 我必须添加某种资源词典吗?

如何才能在我的特定 UserControl 中正确设置所有 Label 的样式?

您可以尝试以编程方式创建样式,然后将其添加到资源中。

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