如何创建可以被两个窗口访问的对象实例 [英] how to create an object instance that could be accessed by two windows
问题描述
在我的wpf应用程序中,我有窗口1,窗口2和一个单独的类文件share.cs,其中包含公共整数变量"a".
每个窗口中都有一个文本框和一个按钮.
在window1的按钮上,我执行以下操作
Window1.cs
In my wpf application, I have window 1, window 2, and a separate class file called share.cs with a public integer variable ''a''
I have a textbox and a button in each of the windows.
on the button in window1, i perform the following operation
Window1.cs
private void button1_Click(object sender, RoutedEventArgs e)
{
share s = new share();
s.a = Convert.ToInt32(textBox1.Text);
Window2 win = new Window2();
win.Show();
}
基本上,我只想将window1上文本框中的值复制到share类中的变量中,然后显示window2.
现在,在window2中,当我单击window2中的按钮时,我想从共享类的变量"a"中检索值,并希望将其显示在window2的文本框中.而且据我了解,window1中的实例``s''与window2的实例不同,这就是为什么我无法正确获取输出的原因.
Window2.cs
Basically, i just want to copy the value from textbox on window1 into the variable in share class, and then display the window2.
Now, In window2, I would like to retrieve the value from variable ''a'' in share class and would like to display it on the textbox in window2, when i click on the button in window2. AND it is my understanding that the instance ''s'' in window1 is different from that of window2, and that is the reason why i am not getting the output correctly.
Window2.cs
private void button1_Click(object sender, RoutedEventArgs e)
{
share s = new share();
textBox1.Text = Convert.ToString(s.a);
}
无论如何,我可以创建一个公共实例并在两个类中使用它吗?如果是这样,我应该在哪里创建实例并使其对两个窗口都可用?我只希望两个窗口都使用同一实例在共享类中使用变量"a".
这就是我在share.cs中拥有的东西.
Is there anyway, that I could create a single common instance and use it in both the classes ? If so, where should I create the instance and make it available to both the windows ? i just want both the windows to use the variable ''a'' in share class using same instance.
This is what I have in share.cs.
public class share
{
public int a;
}
我是一个学习者,请直接回答.没有建议.任何帮助将不胜感激.谢谢. :)
I am a learner and I need direct answers please; not suggestions. Any help would be truly appreciated. Thanks. :)
推荐答案
可以认为是好的设计的最简单方法是使用Form的属性.
还有其他与数据绑定和依赖属性有关的可能性,但是我对WPF的使用还不多,所以我还是用WinForms的方式做一些事情...
1)在Window2中添加属性
The easiest way that could be considered a good design would uses properties of the Form.
There are other possibilities related to data binding and depedency properties but I haven''t played much with WPF yet so I still do some things the WinForms way...
1) Add a property in Window2
// Window2.cs
public int A { get; set; }
2)并在click
处理程序中设置that属性:
2) And the set that property in the click
handler:
// Window.cs
private void button1_Click(object sender, RoutedEventArgs e)
{
Window2 win = new Window2();
win.A = Convert.ToInt32(textBox1.Text);
win.Show();
}
3)单击第二种形式的按钮时获取数据:
3) And the get the data when the button in the second form is clicked:
// Window2.cs
private void button1_Click(object sender, RoutedEventArgs e)
{
textBox1.Text = Convert.ToString(A);
}
这篇关于如何创建可以被两个窗口访问的对象实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!