【问题标题】:Dynamically changing the styles of controls动态改变控件的样式
【发布时间】:2012-01-06 12:38:37
【问题描述】:

我创建了一个屏幕 (Screen1.xaml),其中包含很少的文本框和下拉菜单。由于所有文本框的属性都相同,因此我创建了一个样式文件(stylesheet.xaml),其中包含像这样的宽度、高度、字体大小等属性

<Style x:Key="TextBox.Base" TargetType="Control" BasedOn="{StaticResource TextBlock.Base}">
<Setter Property="Width" Value="250"/>
<Setter Property="FontSize" Value="10"/>
<Setter Property="Height" Value="15"/>
<Setter Property="FontFamily" Value="Arial"/>
</Style>

现在,我想根据某些条件动态更改控件的属性。我想在代码隐藏中实现这一点。请帮忙。

【问题讨论】:

  • 应用新的 Style 资源是否重要,还是 VisualStateManager 会为您提供所需的内容?

标签: c# silverlight xaml styles


【解决方案1】:

您可以选择一种样式并在代码隐藏中更改它。根据您将其包含到项目中的方式,有几种方法:

// the style defined in the app.xaml (you need a key)
Style globalStyle = Application.Current.Resources["Key"] as Style;

// the style defined for a control (you need its key)
UserControl control = ...
Style controlStyle = control.Resources["Key"] as Style;

// the current style of the control
Style currentStyle = control.Style;

像这样改变样式:

style.SetValue(UserControl.FontSizeProperty, (float)10);

编辑: 正如我现在所读到的,更改样式只会影响在 WPF 中使用它的所有控件。在 Silverlight 中,您可以更改所有控件的属性 :(

【讨论】:

    猜你喜欢
    • 2014-04-29
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    • 2018-10-16
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    • 2017-07-15
    相关资源
    最近更新 更多