在自定义控件上设置名称属性会导致编译错误

Setting the Name-attriubute on a custom control results in compilation error

我有一个非常简单的 wpf 自定义控件,它定义了两个构造函数:

public class SomeControl : System.Windows.Controls.Button
{
    public SomeControl() 
    {
    }

    public SomeControl(ISomeService service)
    {
    }
}

此控件在名为 ControlLib 的 class 库中定义。 ISomeService 接口在另一个名为 ServiceContracts 的 class 库项目中定义,ControlLib 引用了它。

解决方案中的第三个项目(称为 FrontEnd)是一个简单的 WPF 项目,我将自定义控件放在 MainWindow 上,如下所示:

<Window x:Class="FrontEnd.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controls="clr-namespace:ControlLib;assembly=ControlLib"
    Height="450"
    Width="800">
<Grid>
    <controls:SomeControl />
</Grid>

到目前为止,一切都按预期正常工作。项目结构大致如下:

当我给服装控件命名时出现问题。当我像这样设置 Name 属性时 <controls:SomeControl x:Name="OhWhy" /> 项目不再编译。我收到以下错误:

Unknown build error, 'Cannot resolve dependency to assembly 'ServiceContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because it has not been preloaded. When using the ReflectionOnly APIs, dependent assemblies must be pre-loaded or loaded on demand through the ReflectionOnlyAssemblyResolve event. Line 8 Position 31.' FrontEnd C:_Data\Tmp\SomeSolution\FrontEnd\MainWindow.xaml 8

我的问题是: 为什么在我添加 Name 属性时它会中断,为什么它首先起作用?

我知道设置名称属性会在设计器生成的 *.g.i.cs 文件中添加一个字段,以便从后面的代码访问控件,但是当我在模板中执行相同操作时,编译也会中断一些没有任何设计器生成文件的资源字典。

以下事情解决了问题,但我不确定原因:

我认为给它起一个名字会发生什么,你会在 FrontEnd 中得到一个类型为 SomeControl 的局部成员变量。这会引入依赖性。在此之前,您只是在资源中有 baml,当 baml 在运行时反序列化时,SomeControl 类型已经加载到 AddDomain 中,并且可以使用反射动态实例化。

这是由 XAML 编译器引起的。请参考以下问题以获取更多信息。

Cannot resolve dependency to assembly 'PostSharp' because it has not been preloaded

解决方案是从 WPF 应用程序项目中添加对 ServiceContracts.dll 的引用。