10

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

thanks

Arian
  • 12,793
  • 66
  • 176
  • 300
  • I go through a few different methods to pass parameters in [this answer](http://stackoverflow.com/a/12444817/200442). It goes over using query string parameters, constructor arguments and a few others. – Daniel Little Sep 24 '12 at 03:30
  • 1
    possible duplicate of [How to pass values (parameters) between XAML pages?](http://stackoverflow.com/questions/12444816/how-to-pass-values-parameters-between-xaml-pages) – Daniel Little Jan 13 '14 at 01:25

4 Answers4

9

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.

H H
  • 263,252
  • 30
  • 330
  • 514
8

Example variable name = DeptName

Declare the variable in App.xaml i.e.

public string DeptName { get; set; }

assign the value in your page-1

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

then call the value in your page-2

 string selected_dept = (App.Current as App).DeptName;
ohlmar
  • 958
  • 8
  • 17
Raj
  • 195
  • 2
  • 6
5

Probably via the Model in an MVVM architecture.

Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222
Joe
  • 122,218
  • 32
  • 205
  • 338
  • But where do you store the model? It's a good idea but just moves the problem around. – H H Oct 26 '11 at 11:47
  • @Henk, a short answer to a short question. But designing an MVVM application is a big subject, the link kindly provided by Klaus in my answer is a good starting point. – Joe Oct 26 '11 at 12:05
1

same as Windows Forms:

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.

Davide Piras
  • 43,984
  • 10
  • 98
  • 147