【问题标题】:Why does this code raise a 'does not exist in namespace' error when it compiles fine?为什么这段代码在编译正常时会引发“命名空间中不存在”错误?
【发布时间】:2016-01-30 02:30:56
【问题描述】:

我正在为 Windows 10 开发基于 XAML 的应用程序。根据this answer,尝试在 Setters 中实现绑定时遇到了问题。这是我的代码:

namespace Sirloin.Helpers
{
    internal class Binding
    {
        public static readonly DependencyProperty ContentProperty = // ...

        public static string GetContent(DependencyObject o) => // ...
        public static void SetContent(DependencyObject o, string value) => // ...
    }
}

这是我的 XAML:

<Page
    x:Class="Sirloin.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Sirloin"
    xmlns:h="using:Sirloin.Helpers"> <!--Some designer stuff omitted for clarity-->

    <Page.Resources>
        <ResourceDictionary>
            <Style x:Key="MenuButtonStyle" TargetType="Button">
                <Setter Property="Background" Value="Transparent"/>
                <Setter Property="h:Binding.Content" Value="Symbol"/> <!--The XAML parser chokes on this line-->
                <Setter Property="FontFamily" Value="Segoe MDL2 Assets"/>
            </Style>
        </ResourceDictionary>
    </Page.Resources>
</Page>

由于某种原因,VS 设计器在到达具有特殊绑定语法的行时似乎会抛出错误;即,将h:Binding.Content 设置为Symbol 的那个。这是消息的截图:

不过,奇怪的是,代码似乎编译得很好。当我在 Visual Studio 中按 Ctrl + B 时,它构建没有错误并成功输出二进制文件。当然,这样做的缺点是我不能使用设计器,它每次构建项目时都会声称 XAML 是“无效标记”。

有人可以推荐我解决这个问题的方法吗?我尝试了 here 重启 Visual Studio 并删除缓存的二进制文件的建议,但它似乎不起作用。

谢谢!

【问题讨论】:

  • @Ryios XAML 引用的代码隐藏在同一个项目中,所以我不明白这是怎么回事。
  • 我怀疑您的代码可以编译,因为设计人员无法确定 Sirloin.Helpers 命名空间中的 Binding 对象,因此它没有在该对象的代码中生成代码。因此没有生成冲突代码,因此生成的代码构建。
  • 为什么你的Binding类被标记为internal?你试过public吗?
  • 我完全错过了你的装订课,抱歉我是盲人。是的,这可能是因为它像 Uchendu 所建议的那样是内部的。 WPF 编辑器在 Visual Studio 进程中运行,因此它无法看到您的 Binding 类,因为它在您的程序集内部。
  • 如果您确定 WPF 编辑器在哪个 .Net 程序集中编译,您可能可以使用 InternalsVisibleToAttribute 将内部对象公开给 Visual Studio。

标签: c# xaml windows-10 win-universal-app uwp


【解决方案1】:

事实证明 Uchendu 是对的:我的一个问题是班级被标记为 internal 而不是 public。我还必须将其标记为sealed,并将依赖属性从字段更改为属性。例如,这个:

public static readonly DependencyProperty BlahProperty = /* ... */;

必须重构为:

public static DependencyProperty BlahProperty { get; } = /* ... */;

WinRT components don't allow exposing public fields.

在这些修改之后,我能够成功构建库。

【讨论】:

    【解决方案2】:

    在开始编译之前清除 Visual Studio 编辑面板,您将不会看到这些烦人的错误消息。也就是说,“X”关闭您当前的所有编辑会话,当然对所有“保存对以下项目的更改”消息回答“是”。

    【讨论】:

      猜你喜欢
      • 2019-01-23
      • 2022-01-25
      • 2016-07-10
      • 1970-01-01
      • 1970-01-01
      • 2011-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多