【问题标题】:Why is an assembly reference removed from the compiled assembly when it's only referenced from xaml当仅从 xaml 引用时,为什么从已编译的程序集中删除程序集引用
【发布时间】:2019-10-22 14:50:15
【问题描述】:

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

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

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

Minimal solution to reproduce via GitHub

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

【问题讨论】:

  • 与 WindowsForms 相比——设计者至少在部分类上工作——XAML 部分是出了名的错误和集成不良。事实上,它花了数年时间才获得对任何 XAML 引起的异常的调试器支持。在此之前,我们基本上不得不猜测 XAML 行可能会导致问题。没关系,在 XAML 错误上,事情仍然会编译 - 使用最后一个好的 XAML 代替!因此,完全有可能这是一个边缘情况,它无法正常工作并将 XAML 引用需求转换为项目引用需求。
  • 其他人似乎也有类似的问题。 XAML 和参考:stackoverflow.com/questions/15816769/…

标签: c# .net wpf xaml roslyn


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多