简体   繁体   English

如何将样式放在单独的.xaml文件中

[英]How to place styles in separate .xaml files

I have an application with a large number of styles that are currently duplicated in the .xaml for each window of the application. 我有一个具有大量样式的应用程序,这些样式当前在应用程序的每个窗口的.xaml中都是重复的。 I would like to be able to reference one file called UiStyles.xaml that contains all of the styles for the application. 我希望能够引用一个名为UiStyles.xaml的文件,其中包含应用程序的所有样式。

After reading a ton of answered questions on here and Google I've tried this: 在这里和谷歌阅读了大量已回答的问题后,我试过这个:

ButtonStyle.xaml: ButtonStyle.xaml:

    <Style TargetType="{x:Type Button}" x:Key="ButtonStyle">
        <Setter Property="Background" Value="Red"/>
        <Setter Property="FontSize" Value="48"/>
    </Style>
</ResourceDictionary>

UiStyles.xaml: UiStyles.xaml:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="ButtonStyle.xaml"/>
    </ResourceDictionary.MergedDictionaries>

    <Style TargetType="Control" /> <!-- Added this based on other user's suggestions to account for .net 4 bug -->
</ResourceDictionary>

MainWindow.xaml: MainWindow.xaml:

<Window x:Class="TestingGround.UI.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <ResourceDictionary Source="Resources/UIStyles.xaml"/>
    </Window.Resources>
    <Grid>
        <Button Click="ButtonBase_OnClick" Content="Test Text"/>
    </Grid>
</Window>

But my button style is not being applied! 但我的按钮样式没有被应用! What am I doing wrong? 我究竟做错了什么?

You have created your button style with an x:Key, but are not referencing that in your button instance. 您已使用x:Key创建了按钮样式,但未在按钮实例中引用该按钮样式。

You need to set the "Style" property of the button like so: 您需要设置按钮的“Style”属性,如下所示:

<Button Click="ButtonBase_OnClick" Style="{StaticResource ButtonStyle}" Content="Test Text"/>

Note when you apply a key to a style, you have to explicitly apply it to the control so 注意将键应用于样式时,必须将其明确应用于控件

<Button Click="ButtonBase_OnClick" 
        Content="Test Text"
        Style={StaticResource ButtonStyle} />

However if you want all buttons to default to the style remove the x:key="ButtonStyle" . 但是,如果您希望所有按钮都默认为样式,请删除x:key="ButtonStyle"

<Style TargetType="...">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM