如何在独立的.xaml文件中放置样式

本文关键字:样式 文件 xaml 独立 | 更新日期: 2023-09-27 17:53:21

我有一个具有大量样式的应用程序,这些样式当前在应用程序的每个窗口的.xaml中重复。我希望能够引用一个名为UiStyles的文件。包含应用程序的所有样式的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:

<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:

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

但是我的按钮样式没有被应用!我做错了什么?

如何在独立的.xaml文件中放置样式

注意,当你对一个样式应用一个键时,你必须显式地将它应用到控件上,所以

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

但是,如果你想让所有按钮默认为样式,请删除x:key="ButtonStyle"

<Style TargetType="...">

你已经用x:键创建了你的按钮样式,但是没有在你的按钮实例中引用它。

你需要像这样设置按钮的"Style"属性:

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