2

在 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 错误吗?有没有绕道?

谢谢!

4

1 回答 1

2

问题解决了!

无论出于何种原因,我都需要参考个人风格。XAML 文件使用包 URI,它必须包含程序集名称。

以下将不起作用:

<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 应用程序程序集中或在单独的自定义控件库中创建自定义控件,此行为都是相同的。

于 2021-01-28T03:55:51.803 回答