Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF passing string to new window

Tags:

c#

wpf

I am trying to pass a string to a new window when it is opened and it is not working. Here is the code in Window 1;

Window 1

private void myButton_Click(object sender, RoutedEventArgs e)
{
    var newMyWindow2 = new myWindow2();
    newMyWindow2.Show();
    newMyWindow2.myString = "The great String Value";
}

In Windows 2 here is my declaration of the string;

Windows 2

public partial class myWindow2 : Window
{
    public string myString { get; set; }
}

When I run it the string is coming out NULL. Why is this?

like image 806
Xaphann Avatar asked Dec 12 '13 15:12

Xaphann


2 Answers

This is what I would do. Pass the string into the constructor, then assign it.

 public myWindow2(string value)
 {
     InitializeComponent();

     this.myString = value;
 }
like image 189
Mike Schwartz Avatar answered Nov 13 '22 12:11

Mike Schwartz


Your showing the window before setting the string value which means the window is loading with a null value for myString. Either pass the string value as a parameter to the constructor or define a default value like string.Empty.

like image 25
Lee Hiles Avatar answered Nov 13 '22 12:11

Lee Hiles