如何在 WPF 表单之间传递数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24590125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass data between WPF forms
提问by user2980509
I need help passing data from one WPF form to another. I have a main window with two other windows that will prompt the user for information. I want to end up with all the information in the first form so that I can store the data later on. The second form must return the Reservation and Room information when you click the OK button on the second form. The third form must return the Person information when you click OK.
我需要帮助将数据从一个 WPF 表单传递到另一个。我有一个带有其他两个窗口的主窗口,这些窗口将提示用户输入信息。我想以第一种形式结束所有信息,以便稍后存储数据。当您单击第二个表单上的 OK 按钮时,第二个表单必须返回预订和房间信息。当您单击确定时,第三个表单必须返回个人信息。
public partial class MainWindow : Window
{
private string message;
public MainWindow()
{
InitializeComponent();
}
protected void Exit_Click(object sender, RoutedEventArgs e)
{
Application.Current.Shutdown();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
protected void Create_Reservation_Click(object sender, RoutedEventArgs e)
{
Reservation PersonReservation = new Reservation();//Create a reservation instance
Room PersonRoom = new Room(); //Create an instance of a room
Person myPerson = new Person();//Create an instance of a person
CreateResRoom createReservationRoom = new CreateResRoom();//Create a instance of the CreateReservation WPF Form
createReservationRoom.Show();
Here it is supposed to set the room, reservation and person instance that I created equil to their corresponding instances in the CreateResRoom class.
这里应该将我创建的房间、预订和人员实例设置为它们在 CreateResRoom 类中的相应实例。
I think the problem lies here, because it keeps continuing before it opens the CreateResRoom form.
我认为问题出在这里,因为它在打开 CreateResRoom 表单之前一直在继续。
PersonRoom = createReservationRoom.myRoom;
PersonReservation = createReservationRoom.myReservation;
}
}
That was my first class, the second and third will follow.
那是我的第一堂课,接下来是第二堂和第三堂课。
public partial class CreateResRoom : Window
{
Person myPerson;
public CreateResRoom()
{
InitializeComponent();
myReservation = new Reservation();
myRoom = new Room();
myPerson = new Person();
}
public Room myRoom
{
get;
set;
}
public Reservation myReservation
{
get;
set;
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void btnOk_Click(object sender, RoutedEventArgs e)
{
myRoom.RoomBeds = txtHeadCount.Text;
myRoom.RoomNumber = 1;
myRoom.RoomPrice = 20;
myRoom.RoomType = cboRoomType.Text;
myReservation.ResEndDate = dpEnd.ToString();
myReservation.ResStartDate = dpStart.ToString();
CreateRes createReservation = new CreateRes();
createReservation.Show();
//I think the same problem lies here that is in the MainWindow.
//我认为MainWindow中存在同样的问题。
myPerson = createReservation.myPerson;
this.Close();
}
}
And the last class follows:
最后一堂课如下:
public partial class CreateRes : Window
{
public Person myPerson
{
get;
set;
}
public CreateRes()
{
InitializeComponent();
myPerson = new Person();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
private void btnOk_Click(object sender, RoutedEventArgs e)
{
myPerson.FirstName = txtFName.Text;
myPerson.LastName = txtLName.Text;
myPerson.IdNumber = Convert.ToInt32(txtIdNumber.Text);
myPerson.PhoneNumber = Convert.ToInt32(txtPhoneNumber.Text);
myPerson.AddressCity = txtAddressCity.Text;
myPerson.AddressStreet = txtAddressStreet.Text;
myPerson.AddressProvince = txtAddressProvince.Text;
myPerson.AddressPostalCode = txtAddressPostalCode.Text;
this.Close();
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
回答by Narendra Singh Rathore
Just make a overload constructor which takes parameters of the window in which you want to retrieve. Example:
只需创建一个重载构造函数,它接受您要检索的窗口的参数。例子:
Suppose we want a user to login from our MainWindow( i.e Login Window ) and we want to pass an int ID / string Email to our second form to retrieve data of logging user. Than We have to first overload our second wpf form constructor. You can either make default constructor to do this or make an overload constructor for this work.
假设我们希望用户从我们的 MainWindow(即登录窗口)登录,并且我们希望将一个整数 ID/字符串 Email 传递给我们的第二个表单以检索登录用户的数据。比我们必须首先重载我们的第二个 wpf 表单构造函数。您可以创建默认构造函数来执行此操作,也可以为此工作创建一个重载构造函数。
SecondForm:
第二种形式:
public secondForm()
{
//Your Default Constructor Logic
}
public secondForm(string email_ )
{
//Your Overload Constructor Logic
}
Now in MainWindow from where we are logging and passing our EMail
现在在我们记录和传递电子邮件的 MainWindow 中
MainWindow:
主窗口:
public void btnLogin()
{
//On Success
SecondWindow sw = new SecondWindow(txtBoxEMail.Content);
sw.Show();
}
回答by Newman
I found another answer that Zarathos posted Jan 16 '13 at 21:43 for a different question
我找到了 Zarathos 于 2013 年 1 月 16 日 21:43 发布的另一个问题的另一个答案
Use a public static class and access it from anywhere.
使用公共静态类并从任何地方访问它。
public static class Globals
{
public static String s_Name = "Mike"; //Modifiable in Code
public const int32 VALUE = 10; // unmodifiable
}
Then you can use it anywhere, provided you are working on the same namespace
然后你可以在任何地方使用它,前提是你在同一个命名空间上工作
string name = Globals.s_Name;
回答by bingles
A pattern you can use for this sort of thing is to have each form be responsible for creating the instance on ok click and then provide the object via a property get.
您可以用于此类事情的一种模式是让每个表单负责在 ok 单击时创建实例,然后通过属性 get 提供对象。
public partial class SomeForm: Window
{
public SomeClass MyProperty { get; private set; }
private void btnOk_Click(object sender, RoutedEventArgs e)
{
this.MyProperty = new SomeClass();
//additional setter logic here
this.Close();
}
}
Then you would access it from a parent form like this (notice the use of ShowDialog() http://msdn.microsoft.com/en-us/library/system.windows.window.showdialog(v=vs.110).aspxfor easy checking of whether ok was clicked or not).
然后你可以从这样的父窗体访问它(注意 ShowDialog() http://msdn.microsoft.com/en-us/library/system.windows.window.showdialog(v=vs.110) 的使用。 aspx以便于检查是否单击了确定)。
protected void Create_Reservation_Click(object sender, RoutedEventArgs e)
{
SomeClass myObj;
SomeOtherClass myOtherObj;
SomeForm myForm = new SomeForm();
if(myForm.Show().Value)
{
myObj = myForm.MyProperty;
}
SomeOtherForm myOtherForm = new SomeOtherForm();
if(myOtherForm.ShowDialog().Value)
{
myOtherObj = myOtherForm.MyOtherProp;
}
//save myObj & myOtherObj or whatever you need to do with them
回答by CyborgDE
Use the "normal way", here is a short overview.
使用“正常方式”,这里是一个简短的概述。
First create a Data Context:
首先创建一个数据上下文:
public class DC_Reservation() : INotifyPropertyChanged {
protected Reservation _PersonReservation ;
public Reservation PersonReservation {
get { return _PersonReservation ; }
set {
_PersonReservation = value;
NotifyPropertyChanged("PersonReservation ");
}
}
protected Room _PersonRoom ;
public Room PersonRoom {
get { return _PersonRoom ; }
set {
_PersonRoom = value;
NotifyPropertyChanged("PersonRoom");
}
}
protected Person _myPerson ;
public Person myPerson {
get { return _myPerson ; }
set {
_myPerson = value;
NotifyPropertyChanged("myPerson ");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged( string PropertyName ) {
if ( PropertyChanged != null ) {
PropertyChanged( this, new PropertyChangedEventArgs( PropertyName ) );
}
}
}
In the MainWindows you can assign and use the dataContext :
在 MainWindows 中,您可以分配和使用 dataContext :
public partial class MainWindow : Window {
DC_Reservation dataContext {
get { return DataContext as DC_Reservation; }
}
private string message;
public MainWindow() {
InitializeComponent();
DataContext = new DC_Reservation();
}
protected void Create_Reservation_Click(object sender, RoutedEventArgs e) {
dataContext.PersonReservation = new Reservation();//Create a reservation instance
dataContext.PersonRoom = new Room(); //Create an instance of a room
dataContext.myPerson = new Person();//Create an instance of a person
CreateResRoom createReservationRoom = new CreateResRoom();//Create a instance of the CreateReservation WPF Form
// I'm not sure whether the next line is required.
createReservationRoom.DataContext = DataContext;
createReservationRoom.Show();
}
}
You can assign the DataContext in the constructor, but I think the better way is to define the DataContext in the MainWindow, in the other windows you can use the DesignContext:
您可以在构造函数中分配 DataContext,但我认为更好的方法是在 MainWindow 中定义 DataContext,在其他窗口中您可以使用 DesignContext:
<Window.DataContext>
<local:DC_Reservation />
</Window.DataContext>
So you can use the same DataContext over all forms ...
因此,您可以在所有表单上使用相同的 DataContext ...
With DataBindings you can bind the input to the field:
使用 DataBindings,您可以将输入绑定到字段:
<TextBox Text="{Binding FirstName, Path=myPerson, Mode=TwoWay}" />

