Visual Studio 2019 WPF 设计器不会显示自定义控件

问题描述

在 WPF (.NET Core) 应用程序项目中,我定义了一个文件夹来包含所有自定义控件(类定义和 UI 样式 .xaml 文件,每个自定义控件都有一对这样的文件)。在同一个程序集中使用这些自定义控件时,我通过合并 /Themes/Generic.xaml 中的所有 UI 样式将认样式与自定义控件相关联,如下所示

<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="/CustomControl/SomeCustomControlStyle.xaml" />
    <!-- Similarly list all other custom control xaml files -->
</ResourceDictionary.MergedDictionaries>

对于每个自定义控件,对应的 xaml 定义其样式,没有 x:Key 如下

<Style targettype="{x:Type SomeCustomControl}" >
    <Setter Parameter="Template">
        <Setter.Value>
            <ControlTemplate targettype="{x:Type SomeCustomControl}">
                <!-- UI DeFinitions -->
            </<ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

所有自定义控件都派生自 Control 并包含一个带有

的静态构造函数
DefaultStyleKeyProperty.OverrideMetadata(typeof(SomeCustomControl),new FrameworkPropertyMetadata(typeof(SomeCustomControl)));

项目构建成功,应用程序运行时显示自定义控件。但是 Visual Studio 设计器无法显示任何自定义控件并报告错误

XDG0062 Cannot locate resource 'customcontrols/somecustomcontrol.xaml'.

我已尝试将认样式从单个 .xaml 文件移动到 Generic.xaml,问题可以解决。但是我有很多自定义控件,使用单个 Generic.xaml 来定义所有 UI 并不是很理想。但是无法在设计器中看到 UI 元素也很不方便。 我错过了什么吗?它是 Visual Studio错误吗?有什么解决办法吗?

谢谢!

解决方法

问题解决了!

无论出于何种原因,我都需要使用包 URI 来引用单个样式的 .xaml 文件,并且它必须包含程序集名称。 以下将不起作用

<ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="pack://application:,/CustomControls/SomeCustomControlStyle.xaml"/>
    </ResourceDictionary.MergedDictionaries>

但以下有效

<ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="pack://application:,/AppAssemblyName;component/CustomControls/SomeCustomControlStyle.xaml"/>
    </ResourceDictionary.MergedDictionaries>

无论是在 WPF 应用程序程序集中创建的自定义控件还是在单独的自定义控件库中创建的自定义控件,此行为都是相同的。