如何使用单独的xaml文件中的样式

时间:2013-01-11 15:17:51

标签: c# wpf xaml binding

我有一个styles.xaml文件,列出了一组颜色。这些颜色定义了应用程序的一个部分中的某些元素如何显示,因此通过转换器使用。

我想在应用程序的另一部分创建这些颜色的图例,并有一个切换按钮列表,我想将背景颜色设置为styles.xaml中定义的颜色。

我是否需要以某种方式将styles.xaml文件包含到定义切换按钮的xaml文件中?或者有什么方法可以直接绑定到这些颜色值?

2 个答案:

答案 0 :(得分:27)

将styles.xaml添加到App.xaml

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

答案 1 :(得分:3)

  

注意以下内容/答案的归属应转至@Chris Schaller。此答案的内容最初是作为@ chameleon86 answer的编辑发布的,并且是rejected(另请参阅this meta)。不过我认为,这是一些有价值的内容,所以我正在重新发布&#39;它

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

要了解其工作原理,在运行时,您的窗口,页面或控件将作为正在运行的应用程序可视树的子元素存在。

您的第一个问题是:

  

&#34;这些颜色定义应用程序的一部分中的某些元素......&#34;

如果您只需要某些 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>