简体   繁体   中英

Change label on a page from another window C# wpf

I have made an application with a NavigationWindow with a page loaded in it. Also is another (normal) window in this project. The names of these windows/pages:

NavigationWindows: MainWindows
Page: Page1
Window: TwitterConnect
Label on Page: label4

I have a label on my Page1 and I want to change it from TwitterConnect. Because I make a new instance of Page1 to call method ConnectToTwitter(), the label on my page doesn't update. Here is the code in de codebehind of TwitterConnect:

        private void button1_Click(object sender, RoutedEventArgs e)
        {  
            string pin = twitpin.Text;    

            Page1 page = new Page1();

            page.ConnectToTwitter(pin, genratedToken);

            this.Close();     
        }

I searched google to find a solution, but I don't get it. I think it has something to do with Dispatcher?!

I'm really a beginner in C#, VS10express and WPF.

How can I change label4 from TwitterConnect? Can you please explain it with a snippet of code?

You are creating a new instance of Page1.xaml from the TwitterConnect window. What you need to do is find a way to access the current instance of Page1.xaml which can easily be acheived by using the DataContext property of the Window class.

Page1.xaml.cs

private void Page_Loaded(object sender, RoutedEventArgs e)
{
    TwitterConnect twitterWindow = new TwitterConnect();
    // this gives TwitterConnect access to Page1's label4 property
    twitterWindow.DataContext = this;
    twitterWindow.Show();
}

TwitterConnect.xaml.cs

private void ButtonClick(object sender, RoutedEventArgs e)
{
    Page1 page1 = (Page1)this.DataContext;

    string pin = twitpin.Text;    
    page1.ConnectToTwitter(pin, genratedToken);
    // Then you can update the label like so:
    page1.Label4.Text = "The text you want to display on the label";
    this.Close();   
}

If I've missed anything out please let me know. Also, I strongly advise against this configuration as it could become a nightmare to maintain. A better approach might be to add a method or property onto Page1.cs to handle setting the text on label4 .

If I have understood your question correctly, you need to refresh the control.

this is a new class

public static class ExtensionMethods
{
 private static Action EmptyDelegate = delegate() { };

 public static void Refresh(this UIElement uiElement)
 {
  uiElement.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate);
 }
}

this is example method in your class (page1?)

private void LoopingMethod()
{
for (int i = 0; i < 10; i++)
{
  label1.Content = i.ToString();
  label1.Refresh();
  Thread.Sleep(500);
}
}

please check this link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM