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

Edw*_*uay 54 c# wpf xaml styles code-behind

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

<TextBlock
Text="Title:"
Width="{Binding FormLabelColumnWidth}"
Style="{DynamicResource FormLabelStyle}"/>
Run Code Online (Sandbox Code Playgroud)

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

TextBlock tb = new TextBlock();
            tb.Text = "Title:";
            tb.Width = FormLabelColumnWidth;
            tb.Style = ???
Run Code Online (Sandbox Code Playgroud)

Sam*_*ack 163

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

tb.SetResourceReference(Control.StyleProperty, "FormLabelStyle")
Run Code Online (Sandbox Code Playgroud)


Ala*_*tts 33

你可以试试:

tb.Style = (Style)FindResource("FormLabelStyle");
Run Code Online (Sandbox Code Playgroud)

请享用!

  • 答案von Samuel更好,因为它相当于XAML中的{DynamicResource},而你的答案将tb.Style更改为资源"FormLabelStyle"的当前值.但是,当资源"FormLabelStyle"发生更改时,tb.Style不会更改. (28认同)
  • 如果您确定资源在此分配后不会发生更改,则更好。 (2认同)

小智 7

最初的问题是如何使它成为动态的,这意味着如果资源发生变化,控件将更新。上面的最佳答案使用了 SetResourceReference。对于 Xamarin 框架,这不可用,但 SetDynamicResource 可用,它完全符合原始海报的要求。简单的例子

        Label title = new Label();
        title.Text = "Title";
        title.SetDynamicResource(Label.TextColorProperty, "textColor");
        title.SetDynamicResource(Label.BackgroundColorProperty, "backgroundColor");
Run Code Online (Sandbox Code Playgroud)

现在调用:

        App.Current.Resources["textColor"] = Color.AliceBlue;
        App.Current.Resources["backgroundColor"] = Color.BlueViolet;
Run Code Online (Sandbox Code Playgroud)

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