Alex Rivera | Logout

Load control style from separate file in wpf

Asked 2012-06-11T10:07:31.307
22

I have the following style added to my Windows.Resources

<Window.Resources>
    ...
    <!--A Style that extends the previous TextBlock Style-->
    <!--This is a "named style" with an x:Key of TitleText-->
    <Style BasedOn="{StaticResource {x:Type TextBlock}}"
       TargetType="TextBlock"
       x:Key="TitleText">
        <Setter Property="FontSize" Value="26"/>
        <Setter Property="Foreground">
            <Setter.Value>
                <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
                    <LinearGradientBrush.GradientStops>
                        <GradientStop Offset="0.0" Color="#90DDDD" />
                        <GradientStop Offset="1.0" Color="#5BFFFF" />
                    </LinearGradientBrush.GradientStops>
                </LinearGradientBrush>
            </Setter.Value>
        </Setter>
    </Style> 
    ...
</Window.Resources>

I have a lot of those styles in my xaml code and I would like to save each component style to an extra file (not an external file).. for example all the styles related to TextBlocks should be in a file called TextBlockStyles.xaml

How would I do this in wpf?

How do I link the style in my project ?

Thanks in advance

Edit
Report

1 Answer

29

You use merged resource dictionaries

In you app.xaml you would use

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary 
                Source="/Your.Assembly.Name;component/TextBlockStyles.xaml"/>
            ... other dictionaries here
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

or directly into a UserControl would be

<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary 
                Source="/Your.Assembly.Name;component/TextBlockStyles.xaml"/>
            ... other dictionaries here
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>

You can shorten Source="..." to just Source="TextBlockStyles.xaml" if the file is in the same assembly and in the root of the project, or alternatively Source="Styles\TextBlockStyles.xaml" if you put the resource dictionary into the folder Styles.

answered 2012-06-11T10:16:26.343

Your Answer