我有一个包含大量样式的应用程序,这些样式目前在应用程序的每个窗口的 .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/