在WPF中在运行时更改样式

我试图允许用户自定义WPF应用程序中的元素。 我想要实现的是,如果我有一个列表框,指定所有表单元素(TextBox,标签等),用户可以选择一个表单元素,并设置样式属性说Label,前景应该是橙色的,其中至于TextBox前景应为黑色,依此类推。 根据我打算应用的样式,所有TextBox都应该看起来很相似。

我无法找到实现这一目标的方法。 我已经尝试了一个示例,其中可以在运行时上载多个预定义的样式。 所以现在,我想找到一种在运行时更改不同元素的属性的方法。

UPDATE:

我试图从后面的代码创建一个新的样式。

XAML

 

并在代码后面,即点击按钮我试过这个:

 Style style = new Style { TargetType = typeof(Label) }; style.Setters.Add(new Setter(Control.ForegroundProperty, Brushes.Black)); Application.Current.Resources["Style1"] = style; 

但它没有得到更新。

谢谢。

您必须确保样式位于App.xaml文件中:

      

代码背后:

 private void ChangeStyle_Click(object sender, RoutedEventArgs e) { Style style = new Style { TargetType = typeof(Label) }; style.Setters.Add(new Setter(Label.BackgroundProperty, Brushes.Aquamarine)); Application.Current.Resources["MyStyle"] = style; } 

如果Style位于WindowWindow.Resources )的资源中,那么您需要编写thisWindow的名称:

 private void ChangeStyle_Click(object sender, RoutedEventArgs e) { Style style = new Style { TargetType = typeof(Label) }; style.Setters.Add(new Setter(Label.BackgroundProperty, Brushes.Aquamarine)); this.Resources["MyStyle"] = style; } 

同样,您可以通过这种方式更改Style :采用现有样式并使用元素。 例:

      

代码背后:

 private void AnotherWay_Click(object sender, RoutedEventArgs e) { label1.Style = (Style)Application.Current.Resources["AnotherWayStyle"]; } 

您是否尝试过使用资源字典?

资源字典

    

XAML用于控制

  

用于在运行时更改样式的代码

  var rd = new ResourceDictionary(); rd.Add("TextColor", "#FFFFFF"); Application.Current.Resources.MergedDictionaries.Add(rd); 

这会将您的新样式与现有样式合并,更改将自动反映在与这些样式链接的所有控件上。

它对我有用,就像一个魅力:

XAML:

      

C#:

 bool Expanded = false; // The event subscription method (for a button click) private void ButtonExpand__Click(object sender, RoutedEventArgs e) { Expanded = !Expanded; Style Style = new Style { TargetType = typeof(TreeViewItem) }; Style.Setters.Add(new Setter(TreeViewItem.IsExpandedProperty, Expanded)); TreePeople.ItemContainerStyle = Style; }