如何在WPF中的两个页面之间传递值

时间:2021-12-25 21:10:40

what is the best practice to pass values between pages in WPF?

在WPF中,在页之间传递值的最佳实践是什么?

thanks

谢谢

4 个解决方案

#1


8  

Your fixed point of reference is the Application object. You can store stuff in the Properties collection:

您的定点引用是应用程序对象。你可以在属性集合中存储:

 string myText = (string)Application.Current.Properties["test"];

Or you can add any kind of data to your derived App class.

或者你可以添加任何类型的数据到你的衍生应用类中。

#2


5  

Probably via the Model in an MVVM architecture.

可能是通过MVVM架构中的模型。

#3


4  

Example variable name = DeptName

示例变量名= DeptName

Declare the variable in App.xaml i.e.

在App.xaml中声明变量,即

public string DeptName { get; set; }

公共字符串DeptName {get;设置;}

assign the value in your page-1

在页面1中分配值。

(App.Current as App).DeptName = "test";

then call the value in your page-2

然后调用页面-2中的值

 string selected_dept = (App.Current as App).DeptName;

#4


1  

same as Windows Forms:

Windows窗体一样:

do not just use global variables or access page's controls from another page. if you have two pages which need to share the same object, e.g. Student, have a method like SetStudent(Student student) in your page or use a property so one page can pass the object Student using that method. You can also have the Get of course, if needed.

不要只使用全局变量或从另一个页面访问页面的控件。如果你有两个页面需要共享相同的对象,例如Student,在你的页面中有一个方法,比如SetStudent(Student),或者使用一个属性,这样一个页面就可以使用这个方法传递给对象Student。当然,如果需要,你也可以使用Get。

#1


8  

Your fixed point of reference is the Application object. You can store stuff in the Properties collection:

您的定点引用是应用程序对象。你可以在属性集合中存储:

 string myText = (string)Application.Current.Properties["test"];

Or you can add any kind of data to your derived App class.

或者你可以添加任何类型的数据到你的衍生应用类中。

#2


5  

Probably via the Model in an MVVM architecture.

可能是通过MVVM架构中的模型。

#3


4  

Example variable name = DeptName

示例变量名= DeptName

Declare the variable in App.xaml i.e.

在App.xaml中声明变量,即

public string DeptName { get; set; }

公共字符串DeptName {get;设置;}

assign the value in your page-1

在页面1中分配值。

(App.Current as App).DeptName = "test";

then call the value in your page-2

然后调用页面-2中的值

 string selected_dept = (App.Current as App).DeptName;

#4


1  

same as Windows Forms:

Windows窗体一样:

do not just use global variables or access page's controls from another page. if you have two pages which need to share the same object, e.g. Student, have a method like SetStudent(Student student) in your page or use a property so one page can pass the object Student using that method. You can also have the Get of course, if needed.

不要只使用全局变量或从另一个页面访问页面的控件。如果你有两个页面需要共享相同的对象,例如Student,在你的页面中有一个方法,比如SetStudent(Student),或者使用一个属性,这样一个页面就可以使用这个方法传递给对象Student。当然,如果需要,你也可以使用Get。