我有一个 WPF (3.5) 应用程序,它使用 Prism 以编程方式实例化多个视图,然后将它们添加到一个区域。我看到的问题是,在视图中作为 DynamicResources 应用的样式在第一次显示视图时没有被应用。如果我们改变屏幕并返回,它将被正确加载,相当肯定这是由于加载和卸载控件。
失败的样式是在我们的根视图中定义的样式。根视图与子视图在同一个类库中,将它们添加到应用程序资源不是一种选择,但它似乎可以解决问题。
我已经在示例应用程序中复制了这个问题。
<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,但是视图非常多,因此我们也希望避免这种解决方案。
更新:发现了这个连接问题,但它真的没有多大帮助。