2013-01-11 32 views
10

我有一個styles.xaml文件,其中列出了一組顏色。這些顏色定義瞭如何顯示應用程序的某個部分中的某些元素,並因此通過轉換器使用。如何使用單獨的xaml文件中的樣式

我想在應用程序的另一部分創建這些顏色的圖例,並且有一個切換按鈕列表,我希望將背景顏色設置爲styles.xaml中定義的顏色。

我需要以某種方式將styles.xaml文件包含到定義切換按鈕的xaml文件中嗎?或者有什麼方法可以直接綁定到這些顏色值?

回答

26

添加styles.xaml到的App.xaml

<Application.Resources> 
    <ResourceDictionary > 
     <ResourceDictionary.MergedDictionaries >  
      <ResourceDictionary Source="styles.xaml"/> 
     </ResourceDictionary.MergedDictionaries> 
    </ResourceDictionary> 
</Application.Resources> 
+0

試過,但我發現了以下錯誤: 所有對象添加到一個IDictionary必須有關鍵屬性或與其關聯的其他某種類型的關鍵字。 styles.xaml只包含一個resourceDictionary,並且所有元素都有鍵(元素的子元素除外)。 –

+1

將按鍵添加到「styles.xaml」中的樣式。或者「styles.xaml」也應該是一個。 –

+1

是的,你需要在styles.xaml – chameleon86

3

Note Attribution for the following content/answer should go to @Chris Schaller . This answer's content was originally posted as an edit to @chameleon86 answer and was rejected (see also this meta). However I think, this is some valuable content and so I am 'reposting' it.

要在styles.xaml提供給應用程序內的所有XAML的定義,添加到styles.xaml的App.xaml

<Application.Resources> 
    <ResourceDictionary > 
     <ResourceDictionary.MergedDictionaries > 
      <ResourceDictionary Source="styles.xaml"/> 
     </ResourceDictionary.MergedDictionaries> 
     <!-- You can declare additional resources before or after Merged dictionaries, but not both --> 
     <SolidColorBrush x:Key="DefaultBackgroundColorBrush" Color="Cornsilk" /> 
     <Style x:Key="DefaultBackgroundColor" TargetType="TextBox"> 
      <Setter Property="Background" Value="{StaticResource DefaultBackgroundColorBrush}" /> 
     </Style> 
    </ResourceDictionary> 
</Application.Resources> 

爲了理解這是如何工作的,在運行時,窗口,頁面或控件將作爲正在運行的應用程序可視化樹的子元素存在。

您最初的問題指出:

"These colors define how certain elements within one part of the application..."

如果你只需要提供給一些 XAML頁面或窗口這些樣式的資源,而不是所有的人,那麼你仍然可以使用這個模式來合併本地資源用於窗口,或直接用於網格或其他控件。

  • 請注意,這樣做只會使這些樣式適用於您聲明資源字典的元素的子元素。

看到它是多麼簡單範圍風格參照單個網格用法:

<Grid> 
    <Grid.Resources> 
     <ResourceDictionary > 
      <ResourceDictionary.MergedDictionaries >  
       <ResourceDictionary Source="styles.xaml"/> 
      </ResourceDictionary.MergedDictionaries> 
      <!-- You can declare additional resources before or after Merged dictionaries, but not both --> 
     </ResourceDictionary> 
    </Grid.Resources> 
    <!-- 
     Grid Content :) 
     --> 
</Grid> 
相關問題