【发布时间】:2018-01-26 04:23:46
【问题描述】:
我正在尝试动态更改画笔的颜色。我写了一个非常简单的例子,但我不明白为什么它不起作用。
我在我的应用程序的 ResourceDictionary 中定义了一种前景色和一个使用该颜色作为 DynamicResource 的前景色:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Color x:Key="Foreground">#FF0000</Color>
<SolidColorBrush x:Key="ForegroundBrush" Color="{DynamicResource Foreground}" />
</ResourceDictionary>
然后,在我的 Window.xaml 中,我使用画笔设置文本块前景:
<Window x:Class="DictionaryColorTests.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel>
<TextBlock Name="mTextBlock" Foreground="{DynamicResource ForegroundBrush}">This is just a text block</TextBlock>
<Button Name="Button1" Click="Button1_Click">Change color</Button>
</StackPanel>
</Grid>
</Window>
最后在我的代码后面,我正在改变颜色:
private void Button1_Click(object sender, RoutedEventArgs e)
{
Application.Current.Resources["Foreground"] = Colors.Green;
}
很遗憾,画笔颜色没有更新。谁能解释一下为什么?
注意:我知道 如果我直接更改画笔的颜色,它可以正常工作,但我试图理解为什么使用颜色作为动态资源的 SolidColorBrush 不会更新其颜色变化时的颜色。
更新:使用样式按预期工作
如果我为文本块使用样式,只需更新颜色,它就可以正常工作并且画笔采用正确的颜色。直接使用画笔和使用样式有什么区别?
<Style TargetType="TextBlock" x:Key="TextBlockStyle">
<Setter Property="Foreground" Value="{StaticResource ForegroundBrush}" />
</Style>
【问题讨论】: