【问题标题】:How can I apply a style to the Window Control in WPF?如何将样式应用于 WPF 中的窗口控件?
【发布时间】:2009-03-26 01:41:35
【问题描述】:

我正在为App.xaml 中的窗口设置样式,如下所示:

<Application x:Class="MusicRepo_Importer.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:System="clr-namespace:System;assembly=mscorlib" StartupUri="TestMaster.xaml">
    <Application.Resources>

        <Style TargetType="Window">
            <Setter Property="WindowStyle" Value="None"></Setter>
        </Style>

    </Application.Resources>
</Application>

我基本上希望每个窗口都将其 WindowStyle 的属性值设置为 None(以删除默认的窗口框架和边框);但它不起作用。

我在这里错过了什么?

【问题讨论】:

    标签: wpf xaml styles


    【解决方案1】:

    我相信您必须为样式命名并将其应用于每个窗口,如下所示..

    在 app.xaml/resources..

    <Style x:Key="MyWindowStyle" TargetType="Window">
        <Setter Property="WindowStyle" Value="None"></Setter>
    </Style>
    

    然后在window.xaml中..

    <Window x:Class="MusicRepo_Importer.MyWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        Title="MyStyledWindow" Style="{StaticResource MyWindowStyle}">
    

    这应该可行,但只是在资源中应用带有 TargetType for Window 的样式不会强制 Window 使用该样式,尽管它似乎适用于其他元素。

    编辑:
    找到了一些关于将默认样式应用于窗口元素的信息..

    如果您提供 TargetType,则所有 该类型的实例将具有 应用的样式。然而派生类型 不会……看来。 不会 为您的所有定制工作 派生/窗口。 将仅适用于 MyWindow。所以 选项是

    使用您指定的键控样式 每个窗口的 Style 属性 想要应用样式。设计师 将显示样式窗口。

    来自问题:How to set default WPF Window Style in app.xaml?

    回答问题的人有一个有趣的想法,即从应用了该样式的基本窗口继承。

    【讨论】:

      【解决方案2】:

      我知道这个问题很老了,但我还是会回答。

      这是在 C# 4.0 中对我来说很好用的代码。 它只是复制资源字典中所有子类的样式。

      public partial class App : Application
      {
          protected override void OnStartup(StartupEventArgs e)
          {
              if (this.Resources.Contains(typeof(Window)))
              {
                  var types = Assembly.GetEntryAssembly().GetTypes();
                  var subTypes = types.Where(x => x.IsSubclassOf(typeof(Window)));
      
                  Style elementStyle = (Style)this.Resources[typeof(Window)];
      
                  foreach (Type subType in subTypes)
                  {
                      if (!this.Resources.Contains(subType))
                      {
                          this.Resources.Add(subType, elementStyle);
                      }
                  }
              }
      
              base.OnStartup(e);
          }
      }
      

      现在您的 App.xaml 样式应该适用于所有窗口。

      附言是的,我知道这不是最干净或最快的方法,但它确实有效。 :)

      【讨论】:

        猜你喜欢
        • 2019-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-11
        • 2021-10-30
        • 2011-06-08
        • 2016-09-18
        • 1970-01-01
        相关资源
        最近更新 更多