如何从两个窗口访问一个类(C#WPF)
我有两个如何从两个窗口访问一个类(C#WPF),c#,wpf,C#,Wpf,我有两个窗口(主窗口,第二窗口),一个类(ExampleClass)在ExampleClass中,两个字符串(Name,SecondName)和带有messagebox的方法,其中应该包含Name+SecondName变量中的文本 因此,我想将一些文本从main窗口添加到ExampleClass Namestring,然后将一些文本从openedSecondWindow添加到ExampleClass SecondNamestring。之后,我想点击main窗口按钮,这应该会给我messagebo
窗口(主窗口,第二窗口)
,一个类(ExampleClass)
在ExampleClass
中,两个字符串(Name,SecondName)
和带有messagebox
的方法,其中应该包含Name+SecondName
变量中的文本
因此,我想将一些文本从main窗口添加到ExampleClass Name
string,然后将一些文本从openedSecondWindow
添加到ExampleClass SecondName
string。之后,我想点击main窗口
按钮,这应该会给我messagebox
两个字符串
Name + SecondName
主窗口:
ExampleClass SomeClass = new ExampleClass();
SomeClass.Name = MainWindowTxtBox.Text;
第二个窗口:
ExampleClass SomeClass = new ExampleClass();
SomeClass.SecondName = SecondWindowTxtBox.Text;
这将仅为一个窗口创建类的新距离,是否可以为两个窗口创建距离 然后,您应该在主应用程序而不是windows中创建类的实例。您可以这样使用:
class ExampleClass
{
public static string Name { get; set; }
public static string SecondName { get; set; }
public static void print()
{
MessageBox.Show(Name + SecondName);
}
}
Class1
{
public ExampleInstance Instance { get; set; }
//Create your Class2 object here with Class2 SecondClassObject = new Class2(this)
}
Class2
{
private Class1 MyCreator;
public Class2(Class1 Creator)
{
this.MyCreator = Creator;
}
//Now you can use the object with: MyCreator.Instance
}
然后在主窗口中
:
ExampleClass.Name = MainWindowTxtBox.Text;
ExampleClass.SecondName = SecondWindowTxtBox.Text;
在第二个窗口中
:
ExampleClass.Name = MainWindowTxtBox.Text;
ExampleClass.SecondName = SecondWindowTxtBox.Text;
最后:
ExampleClass.print();
是的,这是可能的。但是一个班级需要了解另一个班级。试着这样做:
class ExampleClass
{
public static string Name { get; set; }
public static string SecondName { get; set; }
public static void print()
{
MessageBox.Show(Name + SecondName);
}
}
Class1
{
public ExampleInstance Instance { get; set; }
//Create your Class2 object here with Class2 SecondClassObject = new Class2(this)
}
Class2
{
private Class1 MyCreator;
public Class2(Class1 Creator)
{
this.MyCreator = Creator;
}
//Now you can use the object with: MyCreator.Instance
}
希望这有帮助。创建一个singleton():
您的代码如下所示:
class ExampleClass
{
public static string Name { get; set; }
public static string SecondName { get; set; }
public static void print()
{
MessageBox.Show(Name + SecondName);
}
}
Class1
{
public ExampleInstance Instance { get; set; }
//Create your Class2 object here with Class2 SecondClassObject = new Class2(this)
}
Class2
{
private Class1 MyCreator;
public Class2(Class1 Creator)
{
this.MyCreator = Creator;
}
//Now you can use the object with: MyCreator.Instance
}
主窗口
第二窗口
也谢谢,尝试过这种方法,效果也很好……)