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

标签 c# .net wpf xaml

我有一个包含大量样式的应用程序,这些样式目前在应用程序的每个窗口的 .xaml 中都是重复的。我希望能够引用一个名为 UiStyles.xaml 的文件,其中包含应用程序的所有样式。

在这里和谷歌上阅读了大量已回答的问题后,我尝试了这个:

按钮样式.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>

主窗口.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>

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

最佳答案

请注意,当您将键应用于样式时,您必须明确地将其应用于控件,所以

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

但是,如果您希望所有按钮都默认为样式,请删除 x:key="ButtonStyle"

<Style TargetType="...">

关于c# - 如何将样式放在单独的 .xaml 文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30653878/

相关文章:

c# - 是否可以创建自定义 ASP.NET MVC 强类型 HTML Helper?

c# - 是否在此 foreach 循环中创建了垃圾?

.net - .NET 是框架还是库?

c# - 您如何确定 Internet 连接是否可用于您的 WinForms 应用程序?

c# - 为什么 DataGrid 不显示示例设计时数据?

c# - 结合 WPF + WCF + Entity Framework 的好例子

c# - 查找 Click Once 应用程序的 .exe - 任务计划程序

c# - 使用资源键的绑定(bind)字段中的标题文本

c# - 如何删除仅类型不同但使用非默认构造函数的方法之间的重复?

C# I命令语法