如何在代码中分配动态资源样式?

时间:2009-11-18 09:04:13

标签: c# wpf xaml styles code-behind

我想在代码中生成与XAML相同的代码:

<TextBlock
Text="Title:"
Width="{Binding FormLabelColumnWidth}"
Style="{DynamicResource FormLabelStyle}"/>

我可以执行文本和宽度,但如何将动态资源分配给样式:

TextBlock tb = new TextBlock();
            tb.Text = "Title:";
            tb.Width = FormLabelColumnWidth;
            tb.Style = ???

5 个答案:

答案 0 :(得分:160)

如果你想要真正的DynamicResource行为,你应该使用FrameworkElement.SetResourceReference - 即在资源改变时更新目标元素。

tb.SetResourceReference(Control.StyleProperty, "FormLabelStyle")

答案 1 :(得分:33)

您可以尝试:

tb.Style = (Style)FindResource("FormLabelStyle");

享受!

答案 2 :(得分:3)

这应该有效:

tb.SetValue(Control.StyleProperty, "FormLabelStyle");

答案 3 :(得分:1)

最初的问题是如何使其动态化,这意味着如果资源更改,则控件将更新。上面的最佳答案是使用SetResourceReference。对于Xamarin框架,此功能不可用,但SetDynamicResource可用,它完全符合原始发布者的要求。简单的例子

        Label title = new Label();
        title.Text = "Title";
        title.SetDynamicResource(Label.TextColorProperty, "textColor");
        title.SetDynamicResource(Label.BackgroundColorProperty, "backgroundColor");

现在通话:

        App.Current.Resources["textColor"] = Color.AliceBlue;
        App.Current.Resources["backgroundColor"] = Color.BlueViolet;

以这种方式使属性更改为使用该资源的所有控件。这适用于任何财产。

答案 4 :(得分:1)

Application.Current.Resources.TryGetValue("ResourceKey", out var value)