【问题标题】:Global style isn't being applied未应用全局样式
【发布时间】:2015-05-26 12:33:22
【问题描述】:

我有一个资源字典文件:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:local="clr-namespace:TIMS.Common">

<local:ViewModelLocator x:Key="ModelLocator" />

<Style x:Key="DefaultWindowStyle" TargetType="Window">
    <Setter Property="Background" Value="Cyan" />
</Style>

<Style x:Key="DefaultPageStyle" TargetType="Page">
    <Setter Property="Background" Value="Red" />
</Style>

<Style x:Key="DefaultGroupBoxStyle" TargetType="GroupBox">
    <Setter Property="Background" Value="DarkGray" />
</Style>

它被包含在我的 App.XAML 中:

<Application x:Class="TIMS.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local="clr-namespace:TIMS.Common"
         StartupUri="Views/MainWindow.xaml">

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/TIMS;component/Resources.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

但是,除非我在 XAML 中为该对象专门设置了样式,否则此样式不适用。

例子:

<Window x:Class="TIMS.Views.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:TIMS.Views"
    xmlns:nav="clr-namespace:System.Windows.Navigation;assembly=PresentationCore"
    xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
    xmlns:valueConverters="clr-namespace:TIMS.Utils.ValueConverters;assembly=TIMS.Utils"
    x:Name="Main"
    Title="Tote Inventory Management System - Southeastern Grocers"
    Width="1024"
    Style="{StaticResource DefaultWindowStyle}"
    Height="768"
    DataContext="{Binding MainWindowViewModel,
                          Source={StaticResource ModelLocator}}">

如何使这些成为默认样式而不必在每个元素上显式设置它们?

【问题讨论】:

    标签: c# wpf xaml styles


    【解决方案1】:

    例如,如果您希望应用程序中的所有窗口都具有相同的样式,请使用 TargetType Window 删除您的样式的 x:Key 属性。

    拥有 x:Key 属性将强制您在窗口中明确使用该样式以应用它。如果您删除 x:key,那么您应用的所有 Windows 都将默认使用该样式。

    这是一个更详细地解释它的链接:https://msdn.microsoft.com/en-us/library/ms745683(v=vs.110).aspx

    简而言之,如果您希望您的样式是全局的并默认应用于您应用中所有 TargetType 类型的控件,请不要为您的样式设置键。如果您希望样式仅应用于 TargetType 类型的某些控件,请为您的样式设置一个键并在将使用它的控件上显式使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-21
      • 2018-05-01
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-27
      相关资源
      最近更新 更多