Search code examples
c#.netwpfxaml

Error: No matching constructor found on type


I have a WPF application where I am using multiple forms. There is one main form which gets opened when we start the application which is know as MainWindow.xaml. This form then have multiple forms which gets opened depending on the user option. There is a form StartClassWindow.xaml. Currently I am working on this form so I want it to start directly instead of MainWindow.xaml. So to do this I changed the app.xaml startupuri:

<Application x:Class="Class.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         DispatcherUnhandledException="Application_DispatcherUnhandledException"
         StartupUri="StartClassWindow.xaml">
<Application.Resources>

</Application.Resources>
</Application>

But then it started giving error like below:

No matching constructor found on type 'Class.StartClassWindow'. You can use the Arguments or FactoryMethod directives to construct this type.' Line number '3' and line position '9'.

Here is the StartClassWindow.xaml.cs:

namespace Class
{
    public partial class StartClassWindow : System.Windows.Window
    {

       public StartClassWindow(string classData)
       {
          InitializeComponent();
          className = classData;
          function();
       }
       //rest of the code.
    }
}

Solution

  • You need to add a parameter-less constructor to your StartClassWindow like this:

    public StartClassWindow(string classData)
    {
        InitializeComponent();
        className = classData;
        function();
    }
    
    public StartClassWindow()
    {
    
    }
    

    Or if you don't want to have another constructor you can override the OnStartup method in the App.xaml.cs but you should remove the StartupUri="StartClassWindow.xaml" in your App.xaml first. Like below:

    protected override void OnStartup(StartupEventArgs e)
    {
        StartClassWindow st = new StartClassWindow("");
        st.Show();
    }