首页 > 解决方案 > 当仅从 xaml 引用时,为什么从已编译的程序集中删除程序集引用

问题描述

我正在使用面向 .Net Framework 4.7.1 的 Visual Studio 2017 (15.9.7)。
我遇到了没有将传递引用复制到我的输出文件夹的问题。
代码编译没有问题。
我调查了这个问题,发现根本原因是编译的程序集中缺少引用。

我已经提炼了这个问题,这就是我发现的:

我有 2 个类库:

<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>
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 中的一个字段:

ILSpy 截图

通过 GitHub 重现的最小解决方案

这是正常的吗?
这是编译器中的错误吗?
ClassLibary2 显然存在 ClassLibary1 的运行时依赖关系,那么为什么不将引用编译到 ClassLibrary1 的元数据中呢?

标签: c#.netwpfxamlroslyn

解决方案


这是一个已知的 XAML 问题。编译器不会复制仅在 XAML 标记中使用的引用。

解决方法很简单。将程序集的Copy Local属性设置为ClassLibrary2TrueClassLibrary1项目中,或在 C# 中以编程ClassLibrary2方式引用类型。ClassLibrary1


推荐阅读