Reputation: 4443
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
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