Open new (second) window, do something in it and immediately change something in first window WPF C# -


i've got 2 wpf windows , want this: when user clicks on button, located in first window, second window open , in window user click example on button "sword". in first window's textblock, text show "sword" immediately.

i know can transfer text or string text file or xml file or class. don't know how immediately. should use timer or there way?

thanks reply.

the simpiliest way pass first window parameter constructor of second window , change properties of first 1 on button click event handler.

public class secondwindow : window {     private readonly firstwindow _owner;     public secondwindow(firstwindow owner)     {         _owner = owner;     }      private void onswordbuttonclick(object sender, eventargs e)     {         _owner.textblockvalue = "new value";     } } 

you can use more commplex , universal solution eventaggregator or other event-based patterns. event aggregator helps implement subscriber/publisher pattern in low-coupled app.

first create new event property want send between components (or without properties if there no data in event).

next subscribe first window event , change data (string binded label or other model property) in event handler parameter received handler parameter.

finally raise (or publish in other terms) event second window on button click event handler.

as can see both of implementations part of mvvm libraries , this pattern can useful app.

edit

your code examples shows problem nullreferenceexception. happens because calling window1 constructor in wrong manner. write full example below try repeat again more details. change code next one:

public class window1 : window {     private readonly mainwindow _owner;      // constructor of window1 class     public window1(mainwindow owner)     {         initializecomponent();         _owner = owner;     }      private void button_click(object sender, routedeventargs e)     {         _owner.tbw1.text = "sword1";     } }  public class mainwindow : window {     public mainwindow()     {         initializecomponent();     }      private void button_click(object sender, routedeventargs e)     {         // create new instance of window1 , pass current window constructor parameter         var win1 = new window1(this);         win1.show();     } } 

also, there many recommendations you.

  1. it's better use sensible class/method/variable names example optionswindow instead of window1 onchooseswordbuttonclick() instead of button_click. read more naming guidelines on msdn.
  2. read more c# coding conventions on msdn.
  3. read more nullreferenceexception.

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -