c# - Pass Data from Child Window to MainWindow TextBlock -
in example, mainwindow has button opens window2.
window2 has button writes "hello, world!" mainwindow textblock.
project source: https://www.dropbox.com/s/jegeguhycs1mewu/passdata.zip?dl=0
what proper way pass data window2 mainwindow?
private mainwindow mainwindow; public mainwindow mainwindow { get; private set; } public window mainwindow { get; set; } private object mainwindow { get; private set; }; private mainwindow mainwindow = ((mainwindow)system.windows.application.current.mainwindow); this.mainwindow = mainwindow; mainwindow
public partial class mainwindow : window { public mainwindow() { initializecomponent(); } // open window 2 private void buttonwindow2_click(object sender, routedeventargs e) { window2 window2 = new window2(this); window2.left = math.max(this.left - window2.width, 0); window2.top = math.max(this.top - 0, 0); window2.showdialog(); } } window 2
public partial class window2 : window { private mainwindow mainwindow; public window2(mainwindow mainwindow) { initializecomponent(); this.mainwindow = mainwindow; } // write message mainwindow private void buttonmessage_click(object sender, routedeventargs e) { mainwindow.textblockmessage.text = "hello, world!"; } }
the answer you're looking implementation-based , depends heavily on want window2 class do.
private mainwindow mainwindow; this acceptable.
public mainwindow mainwindow { get; private set; } this work doesn't respect naming conventions because it's property. you'd use encapsulation of field or easy access computed value.
public window mainwindow { get; set; } this not acceptable in context because window not contain textblockmessage.
private object mainwindow { get; private set; }; this wouldn't work same reason above.
private mainwindow mainwindow = ((mainwindow)system.windows.application.current.mainwindow); this work , let not keep field reference mainwindow instance in window2 instances. still needs mainwindow everytime click button however.
another interesting way you're doing pass handler child windows @ instanciation:
mainwindow
public partial class mainwindow : window { public mainwindow() { initializecomponent(); } // open window 2 private void buttonwindow2_click(object sender, routedeventargs e) { window2 window2 = new window2(); // no need give reference child window anymore window2.setclickhandler((obj, ev) => { textblockmessage.text = "hello, world!"; // direct access textblock. }); window2.left = math.max(this.left - window2.width, 0); window2.top = math.max(this.top - 0, 0); window2.showdialog(); } } window2
public partial class window2 : window { public window2() { initializecomponent(); } public void setclickhandler(routedeventhandler handler) { // handler given click event. buttonmessage.click -= handler; buttonmessage.click += handler; } } and window2 class has no need know mainwindow.

Comments
Post a Comment