2016-08-25 27 views
0

我在创建的style.xamlResourceDictionary文件中有一个按钮样式。如何在XAML的ResourceDictionary文件中调用样式?

我用这个代码来调用它:

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

但它并没有认识到样式键或者使用静态资源不工作过。如何解决这个问题呢?

我的风格代码:

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

[WPF参考自定义资源的可能的复制定义在另一个xaml文件](http://stackoverflow.com/questions/15775111/wpf-reference-custom-resource-defined-in-another-xaml-file) –

回答

1

您必须导入ResourceDictionary文件在您的XAML,在Resources标签。

事情是这样的:

<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

你有两个选择:

  1. 作为HasNotifications说,embede资源到您想要的样式持有的观点影响
  2. 嵌入的风格应用程序ResourceDictionary。在这种情况下,风格会提供给任何视图应用

下面的代码添加到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> 
相关问题