【问题标题】:Visual Studio 2019 WPF designer won't display custom controlsVisual Studio 2019 WPF 设计器不会显示自定义控件
【发布时间】:2021-01-28 02:13:31
【问题描述】:

在 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 错误吗?有没有绕行的地方?

谢谢!

【问题讨论】:

    标签: c# wpf xaml custom-controls mergeddictionaries


    【解决方案1】:

    问题解决了!

    无论出于何种原因,我都需要参考个人风格。 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 应用程序程序集中还是在单独的自定义控件库中创建自定义控件,此行为都是相同的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-07
      相关资源
      最近更新 更多