简体   繁体   中英

Using another class in WPF C# Project

How to make an object of another class in MainClass.

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {


        public MainWindow()
        {

            InitializeComponent();

        }

        myClass obj = new myClass();
        //obj.Show(); //not possible!!


    }

    public partial class myClass
    {
        void Show()
        {

        }
    }

}

Now In this project, I can't access Show() method using "obj" object. How do I access method of another Class in this project??

You must declare Show as a public void to have access to the method.

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {


        public MainWindow()
        {

            InitializeComponent();
            obj.Show(); //and must be inside of a method, function or constructor.

        }

        myClass obj = new myClass();
        //obj.Show(); //not possible beacause is not a public method.!!


    }

    public partial class myClass
    {
        //public method.
        public void Show()
        {

        }
    }

}

After reading your comments I understood that you are new WPF, and confusing some concepts with Console Applications.

In Console Applications, the Main method acts as an entry point, and everything in the method is executed in an orderly fashion from top to bottom, unless some function calls are made. Consider the following example.

Static void Main(string[] args)
{
   myClass obj = new myClass();
   obj.Show();
}

This code is valid because when the Console Application starts it executes from top to bottom. I mean it creates a myClass object and calls Show method, but in WPF it's different. The only method that executes immediately like Main is MainWindow Constructor. The code after the constructor is not auto executed, unless they are properties, just like a Console Application. I mean the following code will not work properly in a console application.

Static void Main(string[] args)
{
   myClass obj = new myClass();
}
obj.Show();

It's because Show method is called out side of the Main method and the program doesn't know what to do with it. Similarly in WPF, you have to call the Show method in the constructor.

  public MainWindow()
  {
    InitializeComponent();
    obj.Show();
  }

There are many ways to call Show method in WPF, and the above mentioned way is only one of them. The logic Console Applications and Logic of WPF Applications are similar and different at the same time. I suggest you read a few articles or books on WPF to clear things up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM