动态更改控件的样式

时间:2012-01-06 12:38:38

标签: c# silverlight xaml styles

我创建了一个屏幕(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>

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

1 个答案:

答案 0 :(得分:0)

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

// 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中,您可以更改所有控件的属性:(