WPF - 从代码更改全局样式
WPF - change global styles from code
我在 ResourceDictionary 文件中有以下样式
<Color x:Key="LightCyan">LightCyan</Color>
<SolidColorBrush x:Key="LightCyanBrush" Color="{StaticResource LightCyan}" />
<Style x:Key="TextBoxStyle" TargetType="TextBox">
<Setter Property="Width" Value="150" />
<Setter Property="Margin" Value="0,0,0,3" />
</Style>
<Style TargetType="TextBox" BasedOn="{StaticResource TextBoxStyle}">
<Style.Triggers>
<Trigger Property="IsReadOnly" Value="False">
<!-- Change brush color at run time -->
<Setter Property="Background" Value="{StaticResource LightCyanBrush}" />
</Trigger>
</Style.Triggers>
</Style>
我需要在 IsReadOnly = False
和 运行 时从颜色十六进制代码更改文本框背景颜色。
最简单的方法是使用 DynamicResource
而不是 StaticResource
,例如:
<Window.Resources>
<SolidColorBrush x:Key="TextBoxEditableBackgroundBrush"
Color="LightCyan" />
<Style x:Key="TextBoxStyle"
TargetType="TextBox">
<Setter Property="Width"
Value="150" />
<Setter Property="Margin"
Value="0,0,0,3" />
</Style>
<Style TargetType="TextBox"
BasedOn="{StaticResource TextBoxStyle}">
<Style.Triggers>
<Trigger Property="IsReadOnly"
Value="False">
<!-- Change brush color at run time -->
<Setter Property="Background"
Value="{DynamicResource TextBoxEditableBackgroundBrush}" /> <!-- note here -->
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
然后在代码中你只需更改画笔:
var brush = new SolidColorBrush(Colors.Red);
brush.Freeze();
this.Resources["TextBoxEditableBackgroundBrush"] = brush;
我在 ResourceDictionary 文件中有以下样式
<Color x:Key="LightCyan">LightCyan</Color>
<SolidColorBrush x:Key="LightCyanBrush" Color="{StaticResource LightCyan}" />
<Style x:Key="TextBoxStyle" TargetType="TextBox">
<Setter Property="Width" Value="150" />
<Setter Property="Margin" Value="0,0,0,3" />
</Style>
<Style TargetType="TextBox" BasedOn="{StaticResource TextBoxStyle}">
<Style.Triggers>
<Trigger Property="IsReadOnly" Value="False">
<!-- Change brush color at run time -->
<Setter Property="Background" Value="{StaticResource LightCyanBrush}" />
</Trigger>
</Style.Triggers>
</Style>
我需要在 IsReadOnly = False
和 运行 时从颜色十六进制代码更改文本框背景颜色。
最简单的方法是使用 DynamicResource
而不是 StaticResource
,例如:
<Window.Resources>
<SolidColorBrush x:Key="TextBoxEditableBackgroundBrush"
Color="LightCyan" />
<Style x:Key="TextBoxStyle"
TargetType="TextBox">
<Setter Property="Width"
Value="150" />
<Setter Property="Margin"
Value="0,0,0,3" />
</Style>
<Style TargetType="TextBox"
BasedOn="{StaticResource TextBoxStyle}">
<Style.Triggers>
<Trigger Property="IsReadOnly"
Value="False">
<!-- Change brush color at run time -->
<Setter Property="Background"
Value="{DynamicResource TextBoxEditableBackgroundBrush}" /> <!-- note here -->
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
然后在代码中你只需更改画笔:
var brush = new SolidColorBrush(Colors.Red);
brush.Freeze();
this.Resources["TextBoxEditableBackgroundBrush"] = brush;