Reputation: 3977
I am attempting to access a member value in another window or across multiple windows. Is this only possible with static variables? I have two WPF Windows
. MainWindow and TargetWindow.
Here is an example:
Member Class:
class Variables
{
private string _userInput;
public Variables(string input)
{
_userInput = input;
}
public string UserInput
{
set
{
_userInput = value;
}
get
{
return _userInput;
}
}
}
Call and pass value to member in window:
private void txtMainEntry_KeyUp(object sender, KeyEventArgs e)
{
Variables variable;
//Passing user input to class member via constructor
variable = new Variables(txtMainEntry.Text);
//Get value from class member
showUserEntry.Text = variable.UserInput;
if (e.Key == Key.Return & variable.UserInput == "Hello World")
{
TargetWindow tWindow = new TargetWindow();
tWindow.ShowDialog();
this.Close();
}
}
How do I access the same value in another window without using static member:
public partial class TargetWindow : Window
{
public TargetWindow()
{
InitializeComponent();
}
private void lblDisplayVariableValue_Loaded(object sender, RoutedEventArgs e)
{
//How do I call and get the value of the class member
//set in the previous form
}
}
Upvotes: 1
Views: 134
Reputation: 13679
There are couple of approach other then using static value, I have listed a few of them
Approach 1 (Constructors)
private void txtMainEntry_KeyUp(object sender, KeyEventArgs e)
{
Variables variable;
//Passing user input to class member via constructor
variable = new Variables(txtMainEntry.Text);
//Get value from class member
showUserEntry.Text = variable.UserInput;
if (e.Key == Key.Return & variable.UserInput == "Hello World")
{
TargetWindow tWindow = new TargetWindow(variable);
tWindow.ShowDialog();
this.Close();
}
}
public partial class TargetWindow : Window
{
Variables variable ;
public TargetWindow(Variables variable)
{
InitializeComponent();
this.variable = variable;
}
private void lblDisplayVariableValue_Loaded(object sender, RoutedEventArgs e)
{
//use variable field
}
}
Approach 2 (Properties)
private void txtMainEntry_KeyUp(object sender, KeyEventArgs e)
{
Variables variable;
//Passing user input to class member via constructor
variable = new Variables(txtMainEntry.Text);
//Get value from class member
showUserEntry.Text = variable.UserInput;
if (e.Key == Key.Return & variable.UserInput == "Hello World")
{
TargetWindow tWindow = new TargetWindow();
tWindow.Variable = variable;
tWindow.ShowDialog();
this.Close();
}
}
public partial class TargetWindow : Window
{
public Variables Variable { get; set; }
public TargetWindow(Variables variable)
{
InitializeComponent();
}
private void lblDisplayVariableValue_Loaded(object sender, RoutedEventArgs e)
{
//use Variable property
}
}
Note:
above samples are assuming that you have to pass the variable
, you may change as per your needs
other solution is to use attached properties, if above are not feasible then let me know I'll provide a sample for the same.
Upvotes: 2