Search code examples
wpfuser-controlsstylesresourcedictionarydynamicresource

Set Style for user control


I am trying to set a style for my user control. The UserControl is in a project "Controls" and the theme is in a project "MainProject"

<UserControl x:Class="Controls.OutputPanel"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        mc:Ignorable="d" 
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        x:Name="OutputControl"> 
   <!-- Style="{DynamicResource UserControlStyle}"> - I cant set the style here because the Resource Dictionary hasn't been defined yet -->

    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/MainProject;component/Themes/MyTheme.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </UserControl.Resources>

    <!-- Now that the Resource Dictionary has been defined I need to set the style -->      

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>

        <TextBox x:Name="textbox" 
                   ScrollViewer.VerticalScrollBarVisibility="Visible"
                   Text="{Binding ElementName=OutputControl, Path=TextProperty}"
                   IsReadOnly="True"
                   Style="{DynamicResource OutputTextBoxStyle}"/>

    </Grid>

</UserControl>

Solution

  • That should be working fine as far as I can see. Do you get any special warnings or errors or do some parts from the Style not get applied?

    To set the Style after Resources has been set, you can use the following syntax

    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/MainProject;component/Themes/MyTheme.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </UserControl.Resources>
    <UserControl.Style>
        <DynamicResource ResourceKey="UserControlStyle"/>
    </UserControl.Style>
    

    If you're still having problems after this you can compare it to my sample app which I uploaded here: http://www.mediafire.com/?q1v98huubzw02zb