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

问题描述 投票:54回答:4

我想在代码中生成相当于XAML中的这个:

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

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

TextBlock tb = new TextBlock();
            tb.Text = "Title:";
            tb.Width = FormLabelColumnWidth;
            tb.Style = ???
c# wpf xaml styles code-behind
4个回答
33
投票

你可以试试:

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

请享用!


161
投票

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

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

3
投票

这应该工作:

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

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;

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

© www.soinside.com 2019 - 2024. All rights reserved.