Using another class in WPF C# Project - c#

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.

Related

C# 'System.StackOverflowException' in InitializeComponent()

Here are the main parts of the program where the exception seems to be concerned.
using System.Drawing;
using Framework.pages;
namespace Framework
{
public partial class MainWindow : Window
{
public string status;
public MainWindow()
{
InitializeComponent(); // Unhandled exception here
InitializeTheme();
activationStep page = new activationStep();
page.loadPage();
}
// etc etc
This is the abstract class
namespace Framework.pages
{
abstract class template : MainWindow
{
public abstract void loadPage();
public abstract void loadTheme();
}
}
This is the activation step class
using System.Windows.Media;
namespace Framework.pages
{
class activationStep : template
{
public override void loadPage()
{
//this.loadTheme();
}
public override void loadTheme()
{
// Default green activation button
//activateButton.Background = (SolidColorBrush)new BrushConverter().ConvertFromString(Framework.theme.darkGreen);
//activateButton.BorderBrush = (SolidColorBrush)new BrushConverter().ConvertFromString(Framework.theme.borderGreen);
// Set form error color to red
//activationFormError.Foreground = System.Windows.Media.Brushes.Red;
}
// etc etc
The thing is if I comment out these two lines from the MainWindow class:
activationStep page = new activationStep();
page.loadPage();
The program runs fine despite the fact that everything within the activationStep class is commented out anyway (even if they aren't commented out too)? I'm just completely clueless as to why I'm getting this particular exception as there definitely doesn't seem to be any intense loops or anything.
-It's worth noting that there really are not many components loaded into the form and it runs smoothly usually.
You're "newing" up an activationStep, which derives from template, which in turn derives from MainWindow, whose constructor creates a new activationStep... etc, etc.
This loop runs for awhile, and then you get a StackOverflowException.
You'll need to rethink your design.

Pass windows form instance as parameter

I have windows form which is calling another class's method and need to be passed as parameter.
public partial class Form1 : Form
{
private myClass _myClass;
public Form1()
{
InitializeComponent();
_myClass = new myClass(//pass this instance - Form1 - as parameter)
}
}
But I don't know how to pass Form1 instance as parameter? I need to do this, because this other class is creating system tray icon and menu strip and is able to close the parent form.
You'd just do:
_myClass = new myClass(this);
And then change the constructor in myClass:
public class myClass
{
private Form1 theForm;
public myClass(Form1 theForm)
{
this.theForm = theForm;
}
...
}
Now you can access the form from within the class. I think I'd avoid doing this though. Try to leave the form in charge of calling the class and determining when it should close itself.
Having the class hold a reference back to the form that instantiated it, and closing it from within the class seems like it could lead to confusion and maintainability issues down the road.
Simply declare a parameter of type Form in the other's class constructor:
public class myClass
{
private Form otherForm;
public myClass(Form form)
{
otherForm = form;
}
}
and call it from within Form1:
_myClass = new myClass(this);
I can't figure out what you want to achieve. but if you just want to pass this form than you can use this.
_myClass = new myClass(this);
Sure you can:
_myClass = new myClass(this);
Unless I'm missing something, this ought to be fairly straightforward:
public Form1(myClass instance)
{
InitializeComponent();
_myClass = instance;
}

C# - Accessing tree view control from another class

I'm working on a Windows Forms application in C# with Visual Studio 2010.
There is a form mainForm.
mainForm contains a tree view control xmlTreeView.
There is a self-written class myClass.cs.
Now, myClass needs to access the xmlTreeView. However I don't know a) how to access the form and b) which way would be best to do that.
I tried to implement an interface following oleksii's answer but I don't get it. The main form of the application is defined like this:
public interface IMainForm {
TreeView treeView { get; }
}
public partial class mainForm : Form, IMainForm {
public TreeView treeViewControl {
get { return myTreeViewControl; }
}
// Some code here
[...]
RuleTree rt = new RuleTree(); //How do I call this with the IMainForm interface???
}
Another class RuleTree is defined like this:
class RuleTree {
private readonly IMainForm mainForm;
public RuleTree(IMainForm mainForm) {
this.mainForm = mainForm;
}
}
How do I call the constructor of RuleTree with the IMainForm interface???
I would do the following. Don't see it as code, it's just so that you can understand, you can modify it accordingly.
public class MyClass
{
public void MyMethod(YourTreeViewControl treeview)
{
// Do what you need to do here
}
}
Then in your forms code behind just instantiate MyClass and pass an instance of your treeview to it, something like this:
MyClass myClass = new MyClass();
myClass.MyMethod(tvYourTreeViewControl);
Hope this makes sense :)
One of the possible approaches would be to use dependency injection here. MyClass would have a constructor that takes a Form parameter. Thus when you create MyClass it would have the form injected. For example:
Foo
{
Foo(){}
}
Bar
{
private Foo currentFoo;
Bar(Foo foo) //dependency injection
{
currentFoo = foo;
}
public void OtherMethod()
{
//do something with currentFoo
}
}
It will be better to use interfaces (or abstract classes), so instead of Foo you could inject IFoo, this largely decouples your classes, which is a good design decision.
I have commented my code please read comments, I can make solution available as well.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
///
//Declare a static form that will accesible trhought the appication
//create form called frmMain form or any other name
//
public static frmMain MainForm { get; private set; }
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//comment out default application run
//Application.Run(new MainForm());
//create a new instance of your frmMain form
//inside your main form add a tree view
//Loacte this file "frmMain.Designer.cs"
//Change treeView1 from private to public
// public System.Windows.Forms.TreeView treeView1;
MainForm = new frmMain();
//before I show my form I'll change docking of my tree view from myClass
MyClass mine = new MyClass(); //done
MainForm.ShowDialog();
}
}
public class MyClass
{
public MyClass()
{
Program.MainForm.treeView1.Dock = DockStyle.Fill;
}
}
}
This is not possible to access asp.net server side controls into other class other then their cs class e.g
test.aspx is a page
you can access test page controls only in test.aspx.cs
Other then this class this is not possible.

How can I call a methode from the MainWindow without making an instance of it?

I have a method in my Mainwindow, i want to call this method in an other usercontrol.
I dont use a static method because my MainWindow is not Static, and I can't make it static.
So I figured out to use this, but I dont know what comes behind the AS and I dont know if I can put a method is VAR?
I also can't make another MainWindow instance because that gives me a Stackoverflow exception.
How can I solve this?
var myMethode= mainWindow.FindName("MyMethode") as (should be a methode);
if (myMethode!= null)
{
//My code
}
You can define a static method on a class that is not static.
For example:
static void Main()
{
Foo foo = new Foo();
Foo.DoSomething();
foo.DoSomethingElse();
}
public class Foo
{
public static void DoSomething()
{
Console.WriteLine("DoSomething");
}
public void DoSomethingElse()
{
Console.WriteLine("DoSomethingElse");
}
}
But wouldn't it be a better solution to pass the MainWindow as a parameter into the User Control? So the user controls knows to which window it belongs and can access a function on it? (even better to declare an interface for this and pas the interface around).
This would look like:
public interface IWindow
{
string SomeWindowActivity();
}
public class MyUserControl
{
public IWindow Window { get; set; }
public void SomeActionOnUserControl()
{
string data = Window.SomeWindowActivity();
}
}
public class MainWindow : IWindow
{
MyUserControl MyUserControl { get; set; }
public MainWindow()
{
// Link the UserControl to the Window it's one. This can be done trough the
// constructor or a property
MyUserControl.Window = this;
}
public string SomeWindowActivity()
{
// Some code...
return "result";
}
}
Try this
((MyMainWindow)Application.Current.MainWindow).Method()
You don't need to make MainWindow singleton in your case, you have access to it from Application.Current singleton
Application.Current.MainWindow
Hope this helps
Short unswer: you can't. You want to call a instance method, you need to have an instance.
The fact that MainWindow is not static does not prevent you from defining static methods in it, as long as those methods do not use other instance members, so if it a helper method, you can define it static and call from other place, it might a good idea to refactor it out of MainWindow class then.
If it's a nonstatic method, you claim you don't want to create second instance of MainWindow, why not call it on first instance then, by passing it to your control?
Also, if creating another instance of MainWindow gives you stackoverflow, maybe it's because you just did some recurrent call with this method, and it can be fixed?

Calling a function in the Form Class from another Class, C# .NET

Can someone please let me know by some code how I can call a function located in the Form class from another class?
Some code will be of great help!
thanks
EDIT: This is my current code
public partial class frmMain : Form
{
//*******Class Instances*******
ImageProcessing IP = new ImageProcessing();
//********************
public void StatusUpdate(string text)
{
tlsStatusLabel.Text = text;
}//
public frmMain()
{
InitializeComponent();
}//
}
class ImageProcessing
{
private void UpdateStatusLabel(frmMain form, string text)
{
form.StatusUpdate(text);
}//
private UpdateLabel()
{
UpdateStatusLabel(frmMain, "Converting to GreyScale");
}
}
the problem i am having is with frmMain.
A quick and dirty way is to create a reference of the MainForm in your Program.cs file as listed above.
Alternatively you can create a static class to handle calls back to your main form:
public delegate void AddStatusMessageDelegate (string strMessage);
public static class UpdateStatusBarMessage
{
public static Form mainwin;
public static event AddStatusMessageDelegate OnNewStatusMessage;
public static void ShowStatusMessage (string strMessage)
{
ThreadSafeStatusMessage (strMessage);
}
private static void ThreadSafeStatusMessage (string strMessage)
{
if (mainwin != null && mainwin.InvokeRequired) // we are in a different thread to the main window
mainwin.Invoke (new AddStatusMessageDelegate (ThreadSafeStatusMessage), new object [] { strMessage }); // call self from main thread
else
OnNewStatusMessage (strMessage);
}
}
Put the above into your MainForm.cs file inside the namespace but separate from your MainForm Class.
Next put this event call into your MainForm.cs main class.
void UpdateStatusBarMessage_OnNewStatusMessage (string strMessage)
{
m_txtMessage.Caption = strMessage;
}
Then when you initialise the MainForm.cs add this event handle to your form.
UpdateStatusBarMessage.OnNewStatusMessage += UpdateStatusBarMessage_OnNewStatusMessage;
In any UserControl or form associated with the form (MDI) that you want to call, just us the following...
UpdateStatusBarMessage.ShowStatusMessage ("Hello World!");
Because it is static it can be called from anywhere in your program.
You can do that in easy way:
1- create public class and define public static variable like this:
class Globals
{
public static Form1 form;
}
2- in load function at the form write this line:
public partial class Form1 : Form
{
private void Form1_Load(object sender, EventArgs e)
{
Globals.form= this;
}
public void DoSomthing()
{
............
}
}
3- finally, in your custom class you can call all public functions inside the form:
public class MyClass
{
public void Func1()
{
Globals.form.DoSomthing();
}
}
I hope this code will be useful to you:)
It's quite easy. Either pass a reference to an existing form in the call, or create a new instance of your form and then call your method just like any other:
public class MyForm : Form
{
public void DoSomething()
{
// Implementation
}
}
public class OtherClass
{
public void DoSomethingElse(MyForm form)
{
form.DoSomething();
}
}
Or make it a static method so you don't have to create an instance (but it won't be able to modify open form windows).
UPDATE
It looks like the ImageProcessing class never gets a reference to the form. I would change your code slightly:
class ImageProcessing
{
private frmMain _form = null;
public ImageProcessing(frmMain form)
{
_form = form;
}
private UpdateStatusLabel(string text)
{
_form.StatusUpdate(text);
}
}
And then one small tweek in the Form constructor:
ImageProcessing IP = new ImageProcessing(this);
You will have to create a new Form instance and then call it using the instance. If it is static then you can just call it by calling Form1.Method().
Form1 form1 = new Form1();
form1.Method();
I would suggest you move this common method to some other class.
If it is common method to be used in the UI then create a base Form class and derive all your forms with this base form class. Now move this common method to the base form. You can then use the method from any of the Form derived from it.
If the method is not related to the UI, an from your example i understand that it's not, you can create another class that will contain this method and then use it in your Form class and in any other places where you want to use it.

Categories