user594046
user594046

Reputation: 1

C# WPF Update label on window from 2nd cs code file

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!

...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

Answers (3)

Hallgeir Engen
Hallgeir Engen

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

Michael Olesen
Michael Olesen

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

SLaks
SLaks

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

Related Questions