Reputation: 43
I'm relatively new to C# and I have an question regarding how to access a variable from one window in another one. I want to do something like this:
public partial class MainWindow : Window
{
int foo=5;
....
}
and in window2:
public partial class Window2: Window
{
int bar=foo;
}
How should I do that? Thanks in advance...
Upvotes: 2
Views: 10426
Reputation: 95
In a program with fixed variables, the above answers will do good. But if you want to access a variable that is dynamically changed while running, it's better to make a separate class (separate file) to work as an interface between the two window classes.
For the sake of this example, let's assume this 'separate' class is stored inside funkyFolder
. We have to initialize the variable inside this class.
/funkyFolder/DataInterface.cs:
namespace fooDemo.funkyFolder
{
public static class DataInterface
{
public static int fooVal = 0;
}
}
Now, in the first window, you can change the variable data dynamically. Ps: remember to add using fooDemo.funkyFolder
using fooDemo.funkyFolder;
namespace fooDemo
{
public partial class MainWindow : Window
{
private void btnHello_Click(object sender, RoutedEventArgs e)
{
DataInterface.fooVal = 10;
}
}
}
Then, in the second window, you can access the variable without any problem.
using fooDemo.funkyFolder;
namespace fooDemo
{
public partial class SecondWindow : Window
{
public CartPage()
{
System.Diagnostics.Debug.WriteLine(DataInterface.fooVal);
}
}
}
Upvotes: 2
Reputation: 990
You can do it in multiple ways. It depends upon your usage though.
You can expose properties from your Window2 (assuming this form is invoked by MainWindow).
public partial class Window2: Window
{
public string Name {get; set;}
}
Then in MainWindow you can set this property.
Or You can create a singelton as data share. Though, I will not recommend that.
or You can also refer to this link but assuming you are just starting C# I think it might be slightly complicated.
Upvotes: 0
Reputation: 5899
public class WindowBase : Window
{
protected static int foo = 5;
public int Foo
{
get
{
return foo;
}
set
{
foo = value;
}
}
}
public partial class Window1 : WindowBase
{
public Window1()
{
int bar = base.Foo;
}
}
public partial class Window2 : WindowBase
{
public Window2()
{
int bar = base.Foo;
}
}
Upvotes: 2
Reputation: 12439
First of all you'll have to make your variable public
:
public int foo = 5;
For accessing, create instance of MainWindow
:
MainWindow mw = new MainWindow();
bar = mw.foo;
Upvotes: 1
Reputation: 6390
You could put these variables into a static class:
static class MyVariables
{
public static int foo;
}
In MainWindow, you can set the value of this variable:
MyVariables.foo = 5;
And in Window2, you can request the value:
int bar = MyVariables.foo;
Upvotes: 1