Reputation: 1
Newbie here so sorry for the dumb question but I'm having a real problem with this simple little issue for some reason. I have a label and text block on a WPF window and I'm trying to update those from a 2nd cs code file. I've tried the below code but the label is not getting updated...any help or guidance is greatly appreciated!
820File.cs
MainWindow main = new MainWindow();
string status820Text = "Now importing blah";
string status820Label = "Now importing blah";
main.Update820Status(ref status820Text, ref status820Label);
MainWindow.cs
public void Update820Status(ref string status820Text, ref string status820Label)
{
this.StatusLabel.Content =status820Label;
this.StatusTextBlock.Text = status820Text;
}
...and it runs but the Label and TextBlock are not getting updated or rather not displaying the text passed through.
Thanks.
Upvotes: 0
Views: 658
Reputation: 971
The following code works in WPF
axml in your window:
<Label x:Name="lblStatus" Foreground="Red" Content=""/>
code behind in your page:
private void Button_Click(object sender, RoutedEventArgs e)
{
Label lbl = (Label)Application.Current.MainWindow.FindName("lblStatus");
lbl.Content = "New text";
}
Upvotes: 0
Reputation: 473
That would work in WinForms - not in WPF-window.
Try to add a parameter instead. And then read it after the new window is closed (or add a eventhandler to update immediately).
820File.cs
MyWindow w = new MyWindow();
w.MyProperty = "Now importing blah"; // Here we set the initial text
w.ShowDialog(); // Show a modal dialog so this class waits for the changed text
string changedText = w.MyProperty; // Here we read the changed text
MyWindow
public partial class Mywindow : Window
{
public string MyProperty { get; set; }
public MyWindow()
{
}
private void btnOk_Click(object sender, RoutedEventArgs e)
{
MyProperty = "Some new text"; // Set the text to something new
this.Close();
}
}
Upvotes: 0
Reputation: 887453
When you write main = new MainWindow()
, you're creating a brand-new MainWindow
instance that has nothing to do with the existing window on the screen.
You need to pass the existing MainWindow
instance.
Upvotes: 2