gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:41:48 24 4
gpt4 key购买 nike

我有一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com