damix911
damix911

Reputation: 4443

Linked resource dictionary and StaticResource reference at root level

I'm aware of this, which doesn't apply to my case, and this, which I'm not sure whether it can be adapted.

I'm working on a WPF control library, and I don't have an App.xaml file. I use a file called Styles.xml to store common brushes and other resources. In the XAML file of my user control I import the resources and then I try to use brush sBrush as a background.

This works except that at the root level:

<UserControl x:Class="CMControls.TitledWindow"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300"
             Background="{StaticResource ResourceKey=sBrush}"> <!--EXCEPTION!-->

    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary
                 Source="pack://application:,,,/CMControls;component/Styles.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </UserControl.Resources>

    <Canvas Background="{StaticResource ResourceKey=sBrush}" ... <!--Ok.-->
...

I presume this happens because when the root element is instantiated its children are not, including UserControl.Resources. Is there any workaround? Note that in the designer everything works fine, no matter where I make the reference.

Upvotes: 4

Views: 1307

Answers (1)

mahboub_mo
mahboub_mo

Reputation: 3038

Change UserControl Background after Resource Merging line,because you have to add resources before using them!

 <UserControl x:Class="CMControls.TitledWindow"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">

<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary
             Source="pack://application:,,,/CMControls;component/Styles.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>
 <UserControl.Background>  <!--Set background here!-->
    <StaticResource ResourceKey="sBrush"></StaticResource> 
 </UserControl.Background>
 ...

Upvotes: 4

Related Questions