How to place styles in separate .xaml files

I have an application with a lot of styles currently duplicated in .xaml for each application window. I would like to be able to reference a single UiStyles.xaml file containing all the styles for the application.

After reading a ton of answers to questions here and on Google, I tried this:

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

      

But my button style doesn't apply! What am I doing wrong?

+3


source to share


2 answers


Note that when you apply a key to a style, you must explicitly apply it to the control so that

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

      



However, if you want all the default buttons to be styled, remove x:key="ButtonStyle"

.

<Style TargetType="...">

      

+4


source


You styled your button with x: Key, but you don't reference it in your instance.

You need to set the Style property for the button like this:



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

      

+4


source







All Articles