I created a WPF application in c# with 3 different windows, Home.xaml, Name.xaml, Config.xam
l. I want to declare a variable in Home.xaml.cs
that I
There are two different things you can do here (among others; these are just the two that come to mind first).
You could make the variable static on Home.xaml.cs
public static string Foo = "";
You could just pass in the variable to all three forms.
I would go with #2, myself, and if necessary create a separate class that contains the data I need. Then each class would have access to the data.
You can use a static property:
public static class ConfigClass()
{
public static int MyProperty { get; set; }
}
Edit:
The idea here is create a class that you holds all "common data", typically configurations. Of course, you can use any class but suggest you to use a static class. You can access this property like this:
Console.Write(ConfigClass.MyProperty)
The proper way, especially if you ever want to move to XBAPP, is to store it in
Application.Current.Properties
which is a Dictionary object.
App.xaml:
<Application x:Class="WpfTutorialSamples.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
StartupUri="WPF application/ResourcesFromCodeBehindSample.xaml">
<Application.Resources>
<sys:String x:Key="strApp">Hello, Application world!</sys:String>
</Application.Resources>
Code-behind:
Application.Current.FindResource("strApp").ToString()
As other people mentioned before either use App.Current.Properties
or create a static class.
I am here to provide an example for those who need more guidance with the static class.
Right-click your project name in your solution explorer
Add > New Item
chooseClass
give it a name (I usually name it GLOBALS)
using System;
namespace ProjectName
{
public static class GLOBALS
{
public static string Variable1 { get; set; }
public static int Variable2 { get; set; }
public static MyObject Variable3 { get; set; }
}
}
using ProjectName
GLOBALS.Variable1 = "MyName"
Console.Write(GLOBALS.Variable1)
GLOBALS.Variable2 = 100;
GLOBALS.Variable2 += 20;
GLOBALS.Variable3 = new MyObject();
GLOBALS.Variable3.MyFunction();
On a side note, do notice that using the static class as global variables in c# is considered a bad practice (that's why there is no official implementation for globals), but I consider it a shortcut for when I am too lazy haha. It should not be used in the professional environment.
To avoid having to pass around values between windows and usercontrols, or creating a static class to duplicate existing functionality within WPF, you could use:
App.Current.Properties["NameOfProperty"] = 5;
string myProperty = App.Current.Properties["NameOfProperty"];
This was mentioned above, but the syntax was a little off.
This provides global variables within your application, accessible from any code running within it.