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

时间:2016-08-25 21:32:34

标签: xaml resourcedictionary wpf-style

我在创建的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>

2 个答案:

答案 0 :(得分:1)

您必须在Resources代码中导入xaml中的<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> 文件。

这样的事情:

django-admin makemessages --locale=pt_BR

答案 1 :(得分:1)

您有两种选择:

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

    将以下代码添加到App.xaml文件中:

    <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>