C# WPF, Window2 Combobox Default Item to Set MainWindow Background, Error on Initialize -


i have mainwindow , button opens window2.

from window2 set mainwindow's background image combobox.

it works perfectly, if try initialize default combobox item or set default in xaml, error can't find mainwindow.

exception:thrown: "object reference not set instance of object."

mainwindow

// open configure window window2 = new window2(); window2.owner = window.getwindow(this); window2.show(); 

window 2

public window2() {     initializecomponent();      // set default combobox default item     if ((string)combobox1.selecteditem.selecteditem == null)     {         combobox1.selecteditem = "background 1";     } }  // combobox selection changed     private void combobox1_selectionchanged(object sender, selectionchangedeventargs e)     {         // call mainwindow         mainwindow mainwindow = this.owner mainwindow;          // combobox item selection         if ((string)combobox1.selecteditem == "background 1")         {             // background image             imagebrush changebg = new imagebrush(new bitmapimage(new uri(baseurihelper.getbaseuri(this), "resources/bg1.jpg")));              // change mainwindow background             mainwindow.background = changebg;         }     } 

i have tried this, throws error.

mainwindow mainwindow = (mainwindow)application.current.mainwindow; 

exception:thrown: "unable cast object of type 'myproject.window2' type 'myproject.mainwindow'"


Comments