我觉得这个问题很奇怪,可能是 XAML/Visual Studio 错误。我希望其他人发现它不那么奇怪,并解释为什么我所做的事情是错误的,和/或比仅以不同的顺序声明资源更好的解决方法。
我有这个简单的 XAML:
<Window x:Class="TestSOAskArrayXaml.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:system="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:TestSOAskArrayXaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:A x:Key="a1"/>
<x:Array x:Key="listBoxItems" Type="{x:Type system:Double}">
<system:Double>0.25</system:Double>
</x:Array>
</Window.Resources>
<Grid/>
</Window>
当我尝试编译项目时,出现以下错误:
1>...MainWindow.xaml.cs(25,13,25,32): error CS0103: The name 'InitializeComponent' does not exist in the current context
我理解错误的含义,但不明白为什么会发生。 XAML 看起来不错,编译它没有错误,但由于某种原因,自动生成的 .g.i.cs 文件位于
InitializeComponent()
通常不会被创建或使用(即,即使文件来自先前的成功编译,它仍然没有编译到程序集中)。如果我只是颠倒资源的顺序,它就可以正常工作:
<Window.Resources>
<x:Array x:Key="listBoxItems" Type="{x:Type system:Double}">
<system:Double>0.25</system:Double>
</x:Array>
<local:A x:Key="a1"/>
</Window.Resources>
附加信息:
A
是我项目中的任何类(class)。出于此测试的目的,它被声明为 class A { }
,即一个空类,但我首先遇到了这个问题,将转换器实例放入资源中。 A
,例如<system:String x:Key="a1">Some string</system:String>
,错误不会发生。 A
对象和我的数组资源对象,它也可以正常工作! 换句话说,似乎将一个或多个用户定义的类型化对象作为第一个资源元素,然后紧跟一个数组对象,会导致编译失败。其他组合似乎工作得很好。
有人可以解释一下为什么这是预期的行为(除了重新安排我的资源之外,我应该怎么做才能避免它),或者确认我认为这是 XAML 构建过程中的错误并不是完全疯狂?
编辑:
鉴于这是一个实际错误的可能性,我继续在这里打开了一个 Connect 错误报告:https://connect.microsoft.com/VisualStudio/feedback/details/1441123/xaml-fails-to-compile-without-error-if-user-defined-object-is-first-resource-and-followed-immediately-by-x-array-resource
另请参阅相关/类似的堆栈溢出问题:The name 'InitializeComponent' does not exist in the current context : strange behaviour
最佳答案
WPF 团队更新了 Connect 报告(请参阅相关链接),指出该错误的修复将在 .NET 的下一版本中发布:
Posted by Sachin [MSFT] on 3/9/2016 at 3:53 PM
The WPF team has reviewed this issue and fixed in next version of .NET. We thank you for the feedback and consider this issue resolved – WPF team
不幸的是,Microsoft 已停用 Connect 站点,因此不再提供实际报告。但是我在这个问题中问到的问题应该不会再发生了。
关于c# - XAML 无法编译,但没有任何错误消息,如果用户定义的对象是第一个资源并紧跟 x :Array resource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30879531/