WPF控件样式:如何在独立ResourceDictionary中覆盖全局样式单个Setter值
解决方案
你的需求完全可以实现,以下是两种可直接落地的方案:
方案1:样式继承+按需加载(推荐)
该方案完全符合你不重复声明属性、不修改局部视图代码的要求。
- 首先修改
MyCustomResources.xaml中的样式,通过BasedOn继承全局默认TextBlock样式,仅覆盖Foreground属性:
<ResourceDictionary> <Style TargetType="TextBlock" BasedOn="{StaticResource {x:Type TextBlock}}"> <Setter Property="Foreground" Value="Green"/> </Style> </ResourceDictionary>
- 在需要切换样式的时机,将该资源字典加载到应用级资源集合的末尾(WPF资源查找优先级:后加入的资源优先级更高):
var customRes = new ResourceDictionary { Source = new Uri("pack://application:,,,/你的程序集名称;component/MyCustomResources.xaml", UriKind.RelativeOrAbsolute) }; Application.Current.Resources.MergedDictionaries.Add(customRes);
加载完成后全局所有TextBlock会自动应用绿色前景,同时保留App.xaml中定义的斜体、20号字号属性。
方案2:动态修改原有全局样式
如果不需要保留独立的资源文件,也可以直接修改App.xaml中声明的默认样式:
var globalTextStyle = Application.Current.Resources[typeof(TextBlock)] as Style; if (globalTextStyle != null) { // 移除原有红色Foreground设置 var oldForegroundSetter = globalTextStyle.Setters.OfType<Setter>().FirstOrDefault(s => s.Property == TextBlock.ForegroundProperty); if (oldForegroundSetter != null) { globalTextStyle.Setters.Remove(oldForegroundSetter); } // 添加新的绿色Foreground设置 globalTextStyle.Setters.Add(new Setter(TextBlock.ForegroundProperty, Brushes.Green)); }
修改后样式会立即全局生效,无需修改任何页面代码。
内容的提问来源于stack exchange,提问作者chuckp
相关产品推荐
相关产品推荐

