2016-08-25 54 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> 
相關問題