Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No matching constructor found on type

I'm making Windows Phone 7.1 app with Visual Studio Express 2012 for Windows Phone.

I added this namespace to MainPage.xaml:

xmlns:myNameSpace="clr-namespace:MyApp"

And this:

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

And used like this in same file:

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

MyClass looks like this:

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

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

So when I try to Debug it on my cellphone I get the following error:

A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in System.Windows.dll Additional information: No matching constructor found on type 'MyApp.MyClass'.

like image 836
Juho T. Avatar asked Jan 27 '13 20:01

Juho T.


2 Answers

It is because your class is not public. Should be

public class MyClass : ObservableCollection<AnotherClass>

XAML cannot bind to non-public objects/classes/properties

like image 163
David L Avatar answered Oct 14 '22 06:10

David L


You may also get this exception when your code raises a MissingMethodException in the constructor of a xaml object:

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
{}

The xaml parser incorrectly reports that the constructor of the MainWindow class was not found. Looking into the "Inner Exception" of the thrown exception reveals the real reason of the failure.

like image 2
Mohammad Dehghan Avatar answered Oct 14 '22 07:10

Mohammad Dehghan