【问题标题】:WPF Updating styles at runtimeWPF 在运行时更新样式
【发布时间】:2011-01-18 17:05:05
【问题描述】:

我想在运行时动态更新默认的 Window 样式,以便在运行时动态更改 FontSize 和 FontFamily。我发现你的资源字典中的Styles在运行时是密封的,无法更改,所以我使用了以下方法来更新样式:

<Style TargetType="{x:Type Window}">
    <Setter Property="FontFamily" Value="Arial"/>
    <Setter Property="FontSize" Value="12pt"/>
</Style>

使用以下代码:

Style newStyle = (Make a copy of the old style but with the FontSize and FontFamily changed)

// Remove and re-add the style to the ResourceDictionary.
this.Resources.Remove(typeof(Window));
this.Resources.Add(typeof(Window), newStyle);

// The style does not update unless you set it on each window.
foreach (Window window in Application.Current.Windows)
{
    window.Style = newStyle;
}

这种方法有几个问题,我有几个问题是为什么事情会这样。

  1. 为什么样式在运行时被密封,有没有办法让它们解封?
  2. 当我重新添加新样式时,为什么我的所有窗口都没有选择它?为什么我必须手动将其应用到每个窗口?
  3. 有没有更好的办法?

【问题讨论】:

    标签: c# wpf styles font-size resourcedictionary


    【解决方案1】:

    我可能会使用“设置服务”来解决这个问题,该服务公开各种设置的属性,并像正常绑定一样触发 INPC。接下来,我会将样式更改为:

    <Style x:Key="MyWindowStyle">
        <Setter Property="FontFamily" Value="{Binding Path=FontFamily, Source={StaticResource SettingsService}, FallbackValue=Arial}"/>
        <Setter Property="FontSize" Value="{Binding Path=FontSize, Source={StaticResource SettingsService}, FallbackValue=12}"/>
    </Style>
    

    将您的“设置服务”定义为静态资源:

    <services:SettingsService x:Key="SettingsService"/>
    

    然后在每个窗口中确保样式设置为 DynamicResource:

    <Window Style="{DynamicResource MyWindowStyle}" .... >
    

    对于静态资源和动态资源之间的区别,经常存在很多误解,但基本区别在于静态是“一次性”设置,而动态会在资源发生变化时更新设置。

    现在,如果您在“设置服务”中设置这些属性,它们将触发 INPC,这将更新样式,DynamicResource 将选择该样式并相应地更改窗口属性。

    看起来工作量很大,但它给了你一些很好的灵活性,而且所有“繁重的工作”都是纯粹使用绑定完成的。我们在我目前正在处理的项目中使用了类似的技术,因此当用户选择填充/描边颜色时,工具栏中的各种工具会更新以反映新值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-09
      • 1970-01-01
      • 2020-05-08
      • 2018-06-10
      • 1970-01-01
      • 1970-01-01
      • 2021-03-27
      相关资源
      最近更新 更多