2013-01-11 39 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> 
相关问题