【问题标题】:No matching constructor found on type在类型上找不到匹配的构造函数
【发布时间】:2013-01-27 20:32:33
【问题描述】:

我正在使用 Visual Studio Express 2012 for Windows Phone 制作 Windows Phone 7.1 应用程序。

我将此命名空间添加到 MainPage.xaml:

xmlns:myNameSpace="clr-namespace:MyApp"

还有这个:

<Grid.Resources>
        <myNameSpace:MyClass x:Key="referenceToMyClass" />
</Grid.Resources>

并在同一个文件中这样使用:

<ListBox Name="MyListBox"
         Height="{Binding ElementName=ContentPanel, Path=Height}"
         Width="{Binding ElementName=ContentPanel, Path=Width}"
         ItemsSource="{StaticResource referenceToMyClass}"
         DisplayMemberPath="MyAttribute" />

MyClass 如下所示:

namespace MyApp
{
    class MyClass : ObservableCollection<AnotherClass>
    {
        public MyClass()
        {
            Class temp = new AnotherClass("Example attribute");
            Add(temp);
        }

        public void AddAnotherClass(AnotherClass anotherClass)
        {
            Add(anotherClass);
        }
    }
}

所以当我尝试在我的手机上调试它时,我收到以下错误:

System.Windows.dll 中发生了“System.Windows.Markup.XamlParseException”类型的第一次机会异常 附加信息:在类型“MyApp.MyClass”上找不到匹配的构造函数。

【问题讨论】:

    标签: c# silverlight windows-phone-7 xaml exception-handling


    【解决方案1】:

    这是因为您的课程不是公开的。应该是

    public class MyClass : ObservableCollection<AnotherClass>
    

    XAML 无法绑定到非公共对象/类/属性

    【讨论】:

      【解决方案2】:

      当您的代码在 xaml 对象的构造函数中引发 MissingMethodException 时,您也可能会遇到此异常:

      public partial class MainWindow : Window
      {
          public MainWindow()
          {
              InitializeComponent();
      
              var t = Activator.CreateInstance(typeof(T), typeof(int)); // Missing constructor
              // or:
              //this.GetType().InvokeMember("NonExistingMember", BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, null, this, new object[0]);
          }
      }
      
      public class T
      {}
      

      xaml 解析器错误地报告找不到MainWindow 类的构造函数。查看抛出异常的“内部异常”揭示失败的真正原因。

      【讨论】:

      • 那么解决方法是什么?
      • @Chris 为了什么?那个不正确的MissingMethodException?只是不要调用不存在的成员。
      【解决方案3】:

      我添加这个答案是希望它能为那些遇到与我相同的特定问题的人提供一些帮助:

      TeamCity 未能构建多个相关的 SilverLight 项目,报告 resgen.exe 错误和无处不在的通用错误代码,根本没有提供任何洞察力。

      我将 SilverLight 项目从 v3 升级到 v5,允许 TeamCity 构建,但是其中一个 SilverLight 屏幕无法显示任何内容,使用 FireFox 没有报告错误。

      通过使用 Visual Studio 2010 和 IE 进行调试,我得到了与 OP 相同的错误消息,但它在调用 InitializeComponent() 时发生了变化,但不同之处在于该类已经公开?!

      问题是升级后的项目在 resource.resx 文件方面存在问题,在将它们完全从 SilverLight 项目中删除后,整个事情都按预期工作。

      【讨论】:

      • 我在使用 WPF 解决方案时遇到了类似的问题,但我可以更改 XAML 文件中包含与 resx 文件的绑定的任何内容(例如,只需在某处添加空格或删除相同的空格下一次),它的工作原理。不稳定的框架问题。
      • 我有一个类似的问题,我收到来自 InitializeComponent() 的错误消息,错误消息是 resource.resx 缺少承包商。但是解决办法是什么???完全删除 resource.resx 不是一个有效的解决方案。那你有什么建议?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-06
      • 2014-09-28
      • 1970-01-01
      • 2019-09-16
      • 2020-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多