You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF项目从.NET Framework 4.7.2迁移到.NET 5时App.xaml资源异常问题

解决方案

1. 解决BitmapImage IsFrozen警告 + 按钮显示System.Windows.Style问题

  • 给所有BitmapImage资源添加x:Shared="False"属性:.NET Core+版本的WPF默认会自动冻结可冻结类型的资源以优化性能,该属性会让每个资源引用都创建独立实例,避免冻结后无法修改的报错:
<BitmapImage x:Key="BitImageAdd" x:Shared="False" UriSource="Images/iconAdd.png"></BitmapImage>
<BitmapImage x:Key="BitImageDelete" x:Shared="False" UriSource="Images/iconDelete.png"></BitmapImage>
  • 检查按钮的属性绑定逻辑:确认你是将样式赋值给Style属性,而非错误赋值给Content属性,正确写法如下:
<Button Style="{StaticResource btnAdd}" />
  • 校验图片文件属性:右键项目内的图片文件→属性,将「生成操作」设置为资源,「复制到输出目录」设置为不复制,路径解析异常时可替换为Pack URI格式:
UriSource="pack://application:,,,/你的程序集名称;component/Images/iconAdd.png"

2. 解决DataGrid样式内部StaticResource引用报错问题

.NET Core WPF调整了样式内部资源的编译时解析顺序,StaticResource无法匹配同个Style下Resources节点内定义的资源,替换为运行时解析的DynamicResource即可:

<DataTrigger Binding="{Binding State}" Value="3">
    <Setter Property="Background" Value="{DynamicResource Hold}" />
</DataTrigger>
<DataTrigger Binding="{Binding State}" Value="4">
    <Setter Property="Background" Value="{DynamicResource Sent}" />
</DataTrigger>

3. 解决合并资源字典后App崩溃问题

Application.Resources节点下只能存在一个根级ResourceDictionary对象,所有资源(包括合并字典、自定义样式)都要放在该节点内部,不能分散在节点外,正确的App.xaml写法如下:

<Application.Resources>
    <ResourceDictionary>
        <!-- 合并外部资源字典 -->
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="ImageDictionary.xaml" />
        </ResourceDictionary.MergedDictionaries>
        <!-- 原来写在Application.Resources下的所有自定义样式、资源都要放在此处 -->
        <Style TargetType="Button" x:Key="btnAdd" x:Shared="False">
            <Setter Property="Content">
                <Setter.Value>
                    <Image Source="{StaticResource BitImageAdd}"></Image>
                </Setter.Value>
            </Setter>
        </Style>
        <!-- 其他样式定义 -->
    </ResourceDictionary>
</Application.Resources>

内容的提问来源于stack exchange,提问作者Hey Mikey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 23:54:04