我有一个使用Prism的WPF(3.5)应用程序,以编程方式实例化多个视图,然后将它们添加到区域。我遇到的问题是,在视图内作为DynamicResources应用的样式在第一次显示视图时不会被应用。如果我们切换屏幕并回来,它将被正确加载,我相当确定这是由于控件的加载和卸载引起的。
失败的样式是在我们的根视图中定义的样式。根视图与子视图位于同一个类库中,将它们添加到应用程序资源中不是一个选项,但似乎可以解决这个问题。
在MainWindow构造函数中,我添加了另一个TestUC的实例。
当应用程序加载时,第一个实例将具有预期的红色前景色,从构造函数添加的实例将是默认黑色。
有趣的是,如果我将构造函数修改为以下内容,则它可以正常工作。
失败的样式是在我们的根视图中定义的样式。根视图与子视图位于同一个类库中,将它们添加到应用程序资源中不是一个选项,但似乎可以解决这个问题。
我已经在一个示例应用程序中复制了这个问题。
<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>
示例用户控件
<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>
在MainWindow构造函数中,我添加了另一个TestUC的实例。
public MainWindow()
{
InitializeComponent();
root.Children.Add(new TestUC());
}
当应用程序加载时,第一个实例将具有预期的红色前景色,从构造函数添加的实例将是默认黑色。
有趣的是,如果我将构造函数修改为以下内容,则它可以正常工作。
public MainWindow()
{
InitializeComponent();
root.Children.Add(new TestUC());
var x = root.Children[1];
root.Children.RemoveAt(1);
root.Children.Add(x);
}
有没有一个好的解决方案让它工作?将资源添加到应用程序资源中不起作用,因为我们在同一应用程序中有其他 shell,并且这些资源是特定于 shell 的。我们可以将资源字典合并到每个视图中并将它们切换到 StaticResources,但是有很多视图,所以我们也想避免使用该解决方案。
更新:发现了Connect Issue,但真的没有什么帮助。