我想在代码中生成相当于XAML中的这个:
<TextBlock
Text="Title:"
Width="{Binding FormLabelColumnWidth}"
Style="{DynamicResource FormLabelStyle}"/>
我可以做文本和宽度,但是如何将动态资源分配给样式:
TextBlock tb = new TextBlock();
tb.Text = "Title:";
tb.Width = FormLabelColumnWidth;
tb.Style = ???
你可以试试:
tb.Style = (Style)FindResource("FormLabelStyle");
请享用!
如果需要真正的DynamicResource行为,则应使用FrameworkElement.SetResourceReference - 即在资源更改时更新目标元素。
tb.SetResourceReference(Control.StyleProperty, "FormLabelStyle")
这应该工作:
tb.SetValue(Control.StyleProperty, "FormLabelStyle");
最初的问题是如何使其成为动态,这意味着如果资源发生变化,控件将更新。上面的最佳答案使用了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;
以这种方式使用资源为所有控件更改属性。这适用于任何财产。