c# - DynamicResources 无法加载到以编程方式创建的控件中

标签 c# wpf xaml prism dynamicresource

我有一个 WPF (3.5) 应用程序,它使用 Prism 以编程方式实例化多个 View ,然后将它们添加到区域中。我看到的问题是 View 中作为 DynamicResources 应用的样式在第一次显示 View 时没有被应用。如果我们切换屏幕并返回,它将正确加载,可以肯定这是由于加载和卸载控件所致。
失败的样式是在我们的 Root View 中定义的样式。 Root View 与 subview 在同一个类库中,将它们添加到应用程序资源不是一个选项,但它似乎确实解决了问题。

我已经在示例应用程序中复制了该问题。

 <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 的。我们可以将资源字典合并到每个 View 中,然后将它们切换到 StaticResources,但是 View 太多了,所以我们也想避免这种解决方案。

更新:找到这个Connect Issue ,但它确实没有太大帮助。

最佳答案

非常奇怪的问题,我认为它只出现在带有继承标志的依赖属性上。

如果您在 RedTextStyle 中设置背景属性,它将正常更新。

所以我找到了两种方法来解决这个问题:

  1. 在文本元素上使用 ClearValue(TextElement.ForegroundProperty)

  2. 或者使用一些默认值向 App.xaml 添加样式,如下所示:

    <Style x:Key="RedTextStyle" TargetType="TextBlock">
        <Setter Property="Foreground" Value="Black" />
    </Style>
    

关于c# - DynamicResources 无法加载到以编程方式创建的控件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6415271/

相关文章:

c# - 将图像从 xml 中的字节转换为 word 文档

c# - 正则表达式从给定字符串中提取编码类型

c# - 如果前一个线程仍然很忙,如何让 Timer 跳过滴答

c# - 在带有水印的输入上使用必填字段验证器

wpf - 如何在 WPF 中禁用上下文菜单?

c# - Windows 8.1,XAML 绑定(bind) ListView 但不显示第一项

c# - WPF应用程序无法识别Window.Resource

wpf - 将 VB.NET 2.0 Winform 迁移到 3.5 WPF

wpf - Mahapps 弹出窗口未与 caliburn.micro 一起出现

.net - 当绑定(bind)的 ListView 没有项目时显示一些文本