向WPF应用程序添加资源会导致生成错误

时间:2019-04-02 20:19:20

标签: c# wpf

我正在研究《 Head First C#》一书,在向窗口添加资源时始终遇到问题。在添加新资源时,在我创建的任何新WPF应用程序上,这都是100%可重复的错误。解决此问题的唯一方法是注释掉资源,构建和取消注释,如下面的MVCE中所述。包含图像以证明这不是假设或理论场景。

添加资源文件并在WPF项目中使用它的正确步骤是什么?

我正在使用 Visual Studio Community 2017:版本15.9.9 目标框架: .NET Framework 4.6.1


MVCE:

  1. 创建一个新的WPF应用程序。添加课程:

    //MyDataClass.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace XAMLBuildErrorExample
    {
        class MyDataClass
        {
            public string Foo { get; set; }
        }
    }
    
  2. 在MainWindow.xaml中添加资源

    <Window x:Class="XAMLBuildErrorExample.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:XAMLBuildErrorExample"
            mc:Ignorable="d"
            Title="MainWindow" Height="450" Width="800">
        <Window.Resources>
            <local:MyDataClass x:Key="exampleResource" />
        </Window.Resources>
    
        <Grid>
    
        </Grid>
    </Window>
    
  3. 尝试构建。错误“标签'MyDataClass'在XML名称空间'clr-namespace:XAMLBuildErrorExample'中不存在。第11行位置10”。

    enter image description here

  4. 注释掉资源。构建成功:

    enter image description here

  5. 取消注释资源。构建成功但失败了:

    enter image description here

  6. 由于第一张图像中的错误,因此以后对溶液进行的任何清洗都使构建无法进行。

1 个答案:

答案 0 :(得分:1)

问题似乎与初始计算机有关。

在另一个工作站VS Community 2017版本15.9.11上进行了测试,构建成功,没有任何问题。 Build> Clean>构建没有问题。