Sturm
Sturm

Reputation: 4125

Using a class in WPF

When I'm developing a ConsoleApp there is no problem to use classes in my Main that I've created in separated files (Project Menu --> Add Class). But later, when I try to do it in WPF that class is not recognized. I have made sure that the namespace it's the same both in my "MainWindow.xaml.cs" and my Class Canal.cs. When I define that same class but inside MainWindow.xaml.cs everything works fine, but due to the extension of the code I prefer separate it.

MainWindow.xaml.cs:

//using      
 namespace Tcomp
    {
     public partial class MainWindow : Window
            {
        void MainWindow_Loaded(object sender, RoutedEventArgs e)
                { //Stuff but I can't use class created outside of MainWindow.xaml.cs
}
}
}

Canal.cs

//using
    namespace TComp
    {
        public class Canal
        { //some propreties here
    }
    }

Thanks.

Upvotes: 0

Views: 11493

Answers (4)

Mike Nakis
Mike Nakis

Reputation: 62100

namespace Tcomp

namespace TComp

You know that C# is case-sensitive, right?

Upvotes: 1

Alexandru Dicu
Alexandru Dicu

Reputation: 1235

You must either instantiate the Canal class:

var myClass = new Canal();

and then you can use the properties from it. Make myClass a private member of your MainWindow.xaml.cs and you can access it anytime. Or the second way, make Canal class static and then you can access it from everywhere. Hope this helps.

Upvotes: -1

Alexander Bell
Alexander Bell

Reputation: 7918

@mcxiand already answered your question. I would like to add another option: you can use a

public partial class MainWindow : Window

and add it to as many files as you want containing your code, thus there will be no need to create additional class library. The key word here is partial, which allows the code encapsulated in this class to spread over multiple files (.cs).

Upvotes: -1

mark vanzuela
mark vanzuela

Reputation: 1391

Create the class inside a library project not on a console app. And on your WPF project, add a project reference to the library project you have created.

Upvotes: -1

Related Questions