背景:
使用 Visual Studio 2017 v15.4(没有 ReSharper 或任何奇怪的扩展)
Repro 解决方案包括 2 个项目:
- WPF 项目:.NET 4.6.1,使用 NuGet PackageReference 格式
- 类库:NET Standard 2.0
这两个项目都System.ComponentModel.Annotations
安装了 NuGet 包。
问题
将 WPF 项目的 NuGet 格式从旧packages.config升级到新PackageReference后,我开始遇到设计时错误:
首先,以下 ViewModel 代码可以正常工作:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public class MainWindowViewModel
{
public ValClass MyProp => new ValClass();
}
public class ValClass : IValidatableObject
{
//Implementation stuff
}
但是,如果我随后在我的 NET Standard 项目中定义了一个相同的类,并将其作为一个类型包含在我的 ViewModel 中,则会产生错误。
比较这两个类的 IValidatableObject 上的 F12:
WPF 版本:
#region Assembly System.ComponentModel.DataAnnotations, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.1\System.ComponentModel.DataAnnotations.dll
#endregion
NET 标准 2.0 版本:
#region Assembly System.ComponentModel.Annotations, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// C:\Users\a0110\.nuget\packages\system.componentmodel.annotations\4.4.0\ref\netstandard2.0\System.ComponentModel.Annotations.dll
#endregion
很明显,在具有不同名称的程序集中定义了相同的类型和命名空间——而不仅仅是程序集版本。
如何让 XAML 设计器成功找到需要使用的任何程序集IValidatableObject
?
我尝试过的事情
- 安装 VS v15.5 预览版并将 WPF 项目定位到 .NET 4.7(也是 15.5 预览版 2 和 3,.NET 4.7.1)
- 添加对 WPF 项目的旧
System.ComponentModel.DataAnnotations
引用(有和没有 NuGet 版本) - 恢复到 packages.config 格式(这实际上并没有成功;看来我被 PackageReference 困住了!)
- 从项目的输出文件夹中获取 System.ComponentModel.Annotations.dll 的副本并直接引用它(VS 不允许我这样做)
- 添加
bindingRedirect
到我的 App.config - 添加
<DependsOnNETStandard>True</DependsOnNETStandard>
到 .csproj - 添加
<DependsOnNETStandard>netstandard2.0</DependsOnNETStandard>
到 .csproj - 添加
<_HasReferenceToSystemRuntime>true</_HasReferenceToSystemRuntime>
到 .csproj - 将 NETStandard.Library NuGet 包添加到 WPF 项目
更新
对于受此问题困扰的其他任何人,我找到了一种解决方法:
- 在您的 NET Standard 项目用于 IValidatableObject 的硬盘驱动器上找到 System.ComponentModel.Annotations.dll。将其复制到项目中的某个位置。
- 从您的解决方案中卸载 System.ComponentModel.Annotations NuGet 包
- 为您的 NET Standard 项目提供对您复制的 DLL 的直接引用
- 为您的 WPF 项目提供对标准程序集 System.ComponentModel.DataAnnotations 的引用
- 将您的 WPF 项目升级到 .NET 4.7.1
- 编译。您的 WPF 设计时应该没有此错误。
.