我试图在另一个窗口或多个窗口中访问成员值。这只能用静态变量吗?我有两个WPF Windows
。 MainWindow 和 TargetWindow 。
以下是一个例子:
会员类:
class Variables
{
private string _userInput;
public Variables(string input)
{
_userInput = input;
}
public string UserInput
{
set
{
_userInput = value;
}
get
{
return _userInput;
}
}
}
在窗口中调用并将值传递给成员:
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();
}
}
如何在不使用静态成员的情况下访问另一个窗口中的相同值:
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
}
}
答案 0 :(得分:2)
除了使用静态值之外还有几种方法,我已经列出了其中一些
方法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
}
}
方法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:
以上样本假设您必须通过variable
,您可以根据需要进行更改
其他解决方案是使用附加属性,如果上述不可行,请告诉我,我将提供相同的样本。