如何在 XAML 中调用 ResourceDictionary 文件中的样式?

How to call a Style in a ResourceDictionary file in XAML?

我在创建的 style.xaml ResourceDictionary 文件中有一个按钮样式。

我用这段代码来调用它:

<Button Style="{DynamicResource exitButton}" />

但它无法识别样式键,或者使用 StaticResource 也不起作用。如何解决这个问题?

我的风格代码:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Style x:Key="exitButton" TargetType="Button">
    <Setter Property="Width" Value="22"/>
    <Setter Property="Height" Value="32"/>
    <Setter Property="Background" Value="#FF7070"/>
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="Button">
          <Border Width="{TemplateBinding Width}"
                  Height="{TemplateBinding Height}"
                  HorizontalAlignment="Center"
                  VerticalAlignment="Center">
            <TextBlock Text="X"
                       FontSize="15"
                       Foreground="White"
                       FontWeight="Bold"/>
          </Border>
        </ControlTemplate>
      </Setter.Value>
    </Setter>
  </Style>
</ResourceDictionary>

您必须在 xaml 的 Resources 标签中导入 ResourceDictionary 文件。

像这样:

<UserControl blablabla...>
  <UserControl.Resources>
    <ResourceDictionary>
      <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="/*PROJECT_NAME*;component/*FOLDER_PATH*/style.xaml"/>
      </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
  </USerControl.Resources>

  <!-- the content -->

  ...

  <Button Style="{StaticResource exitButton}"/>

</UserControl>

您有两个选择:

  1. 正如 HasNotifications 所说,将资源嵌入到您希望样式生效的视图中
  2. 将样式嵌入应用程序 ResourceDictionary。在这种情况下,该样式将可用于应用程序上的任何视图

Add the following code to the App.xaml file:

<Application x:Class="WpfApp1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp1"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/*PROJECT_NAME*;component/*FOLDER_PATH*/style.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>