类型上找不到匹配的构造函数

9

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

我在MainPage.xaml中添加了这个命名空间:

xmlns:myNameSpace="clr-namespace:MyApp"

And this:

<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" />

我的类看起来像这样:

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'上找不到匹配的构造函数。

3个回答

17

这是因为您的类并非public。应改为

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类的构造函数未找到。查看抛出异常的“内部异常”可以揭示失败的真正原因。


那么这个问题的解决方案是什么? - Hungry Beast
@Chris 为什么?针对那个不正确的“MissingMethodException”吗?只需不要调用不存在的成员即可。 - Mohammad Dehghan

0
我写这个答案希望它能够对那些遇到和我相似问题的人提供一些帮助:
TeamCity在构建多个依赖于SilverLight项目时出现了resgen.exe错误,并显示没有任何可用信息的普遍错误代码。
将SilverLight项目从v3升级到v5后,TeamCity成功构建,但其中一个SilverLight屏幕无法显示任何内容,使用FireFox也未报告错误。
通过在Visual Studio 2010和IE中进行调试,我得到了与OP相同的错误消息,只是在调用InitializeComponent()时发生了差异,但是类已经是public了?
问题在于升级后的项目在resource.resx文件上存在问题,将其从SilverLight项目完全删除后,整个项目正常工作。

我正在使用一个类似的 WPF 解决方案遇到问题,但是我可以更改包含绑定到 resx 文件的 XAML 文件中的任何内容(例如,在某个地方添加空格或下一次删除相同的空格),这样就可以解决问题了。框架问题不稳定。 - Travis
我有一个类似的问题,当我调用InitializeComponent()时,出现了错误,错误信息显示缺少resource.resx的构造函数。但是解决方案是什么呢?完全删除resource.resx不是一个有效的解决方案。那么你有什么建议呢? - Gil Epshtain

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接