0

I have two page (main page / second page). I create a string in Mainpage.xaml.cs but I want to use that string in second page. how can I do it?

Per Henrik Lausten
  • 21,331
  • 3
  • 29
  • 76

3 Answers3

0

You can do it by having another static class with a static string as its member, likewise:

public static class stringWrapper{
 public static string message{get; set;}
}

and then set it in the MainPage.xaml.cs and then get its value in the secondPage.xaml.cs, likewise:

MainPage.xaml.cs :

stringWrapper.message = "Whatever your string is";

secondPage.xaml.cs :

string msg = stringWrapper.message;

Hope this helps.

0

You can have different solutions to this :

  1. Make the string a public static property in a wrapper class as @cybertronhac mentioned.
  2. Use the Messenger pattern (from Mvvm Light for example) to send your string to your second page when ever it's requested.
  3. Change the DataContext of the object in SecondPage that needs to be bound to the string object,to be the MainPage.xaml.cs class
AymenDaoudi
  • 7,811
  • 9
  • 52
  • 84
0

In the App.xaml.cs, outside the constructor "public App()" declare a variable(suppose 'a'). Made it public static. Then in the Mainpage.xaml.cs put your string in that variable 'a'. As you can access 'a' from any page of your project, you will get your desired string. I hope this will help. A sample is given below.

In the App.xaml.cs Page:

public static string a = "";

In the MainPage.xaml.cs Page:

App.a = "My Name is Neymar.";

Now you can show your string in a console in second page or you can use it for another purpose. Your valuable string is in variable 'a' which can be accessed by writing "App.a":

Debug.WriteLine("" + App.a);