I have a WPF (3.5) application using Prism to programmatically instantiate a number of views and then add them to a region. The problem I am seeing is that styles inside the view that are applied as DynamicResources are not being applied the first time the view is shown. If we change screens and come back, it will be loaded properly, fairly certain this is due to loading and unloading the control.
The styles that fail are the ones are defined in our root view. The root view is in the same class library as the child view, adding them to Application Resources is not an option, however it does appear to fix the problem.
I've replicated the problem in a sample application.
<Window x:Class="ProgrammaticDynamicResourceProblem.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:l="clr-namespace:ProgrammaticDynamicResourceProblem"
Height="350" Width="525">
<Window.Resources>
<Style x:Key="RedTextStyle" TargetType="TextBlock">
<Setter Property="Foreground" Value="Red" />
</Style>
</Window.Resources>
<StackPanel x:Name="root">
<l:TestUC /> <!-- Will have a foreground of Red -->
</StackPanel>
</Window>
The sample UserControl
<UserControl x:Class="ProgrammaticDynamicResourceProblem.TestUC"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<TextBlock Text="Test Text" Style="{DynamicResource RedTextStyle}" />
</UserControl>
In the MainWindow constructor I add another instance of a TestUC.
public MainWindow()
{
InitializeComponent();
root.Children.Add(new TestUC());
}
When the application loads, the first instance will have a foreground of Red as expected, the one added from the constructor will be the default black.
Interestingly, if I modify the constructor to look like this, it works.
public MainWindow()
{
InitializeComponent();
root.Children.Add(new TestUC());
var x = root.Children[1];
root.Children.RemoveAt(1);
root.Children.Add(x);
}
Is there a decent solution to getting this to work? Adding the resources to the Application Resources doesn't work because we have other shells in the same application and these resources are shell specific. We can merge the resource dictionaries into each of the views and switch them to StaticResources, but there are quite a few views, so we would like to avoid that solution as well.
UPDATE: Found this Connect Issue, but it really didn't help much.