c# - 当仅从 xaml 引用时,为什么从已编译的程序集中删除程序集引用
问题描述
我正在使用面向 .Net Framework 4.7.1 的 Visual Studio 2017 (15.9.7)。
我遇到了没有将传递引用复制到我的输出文件夹的问题。
代码编译没有问题。
我调查了这个问题,发现根本原因是编译的程序集中缺少引用。
我已经提炼了这个问题,这就是我发现的:
我有 2 个类库:
- ClassLibrary1 有一个 xaml UserControl,它引用 ClassLibrary2 中的 BitmapImage:
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:media="clr-namespace:ClassLibrary2;assembly=ClassLibrary2"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Image Source="{x:Static media:MediaResourceImages.Autofocus_16}" />
</UserControl>
- ClassLibrary2 有一个在其中编译的 png 资源文件,以及一个从 png 创建的公共静态类中的公共静态只读 BitmapImage 字段:
using System;
using System.Windows.Media.Imaging;
namespace ClassLibrary2
{
public static class MediaResourceUris
{
public const string Autofocus_16 = "pack://application:,,,/ClassLibrary2;component/Resources/Autofocus_16.png";
}
public static class MediaResourceImages
{
public static readonly BitmapImage Autofocus_16 = new BitmapImage(new Uri(MediaResourceUris.Autofocus_16));
}
}
编译成功后,ILSpy 显示 ClassLibrary1 没有对 ClassLibrary2 的引用,即使 baml 引用了 ClassLibrary2 中的一个字段:
这是正常的吗?
这是编译器中的错误吗?
ClassLibary2 显然存在 ClassLibary1 的运行时依赖关系,那么为什么不将引用编译到 ClassLibrary1 的元数据中呢?
解决方案
这是一个已知的 XAML 问题。编译器不会复制仅在 XAML 标记中使用的引用。
解决方法很简单。将程序集的Copy Local
属性设置为ClassLibrary2
在True
库ClassLibrary1
项目中,或在 C# 中以编程ClassLibrary2
方式引用类型。ClassLibrary1
推荐阅读
- amazon-web-services - Cloudfront 如何分发 AWS KMS 密钥以获取静态加密的 S3 图像?
- c# - 在 DirectX 视频上绘制/渲染文本(PictureBox 控件作为所有者)
- pixi.js - Pixi.js 与 Pixi.min.js 的区别?
- java - 如何在java中初始化另一个类的变量?
- google-analytics - 如何在 Google Analytics/Data Studio 中过滤具有特定主机名的上一页路径
- apache-kafka - kafka客户端可以选择特定分区消费吗?
- javascript - Javascript - 排除特定表单标签之外的所有内容
- html - 如何设置数据错误的字体系列
- eclipse - Java(Mac OS):从文件中重新读取对象时,将我的对象写入文件会导致测试出现乱码
- asp.net-mvc - 将一个文件夹移回服务器 MVC