Referring to controls on other windows in WPF
Hi,
I'm quite new at programming in WPF and I have a question. I have two windows: one window with a button and, say, a textbox, that is started up by default (by setting Startup URI) and another one that is created by pressing this button on the first window.
This second window has some code in it. Its output should be directed to the textbox on the first window. With the old window forms this was easy, but I can't seem to make it happen in WPF.
My question is: how can I refer to a control on a window which is not the window in which the referring code lies?
Thanks!
Re: Referring to controls on other windows in WPF
Re: Referring to controls on other windows in WPF
Basically the reason why it was easy in windows forms is because you have what are called default form instances. Forms/Windows are classes just like any other class in the .NET framework and as such they require that you create an instance of them before you can use some methods within them (such as the .Show method of a form/window). So in Windows Forms, you basically have one instance of each form in your project created for you, so when you do Form1.Show you are just referring to this default instance.
In WPF however, you do not have default instances of windows/forms so you have to do things the 'proper' way and create an instance yourself (which you will probably have realised and done otherwise you would not have been able to make your second window appear).
So the problem then as you have found is that you cant just refer to the default instance when you want to access that window from another form, so you have a few options.
The first option is useful if you only ever intend to have one instance of a particular window showing at any one time. What you can do is loop through the window collection in Application.Current.Windows and do a simple IF statement to see if the window you are currently on is the same Type as the window you are trying to find, then cast it to that Type and access whichever controls or properties you like on it. Here is an example:
vb.net Code:
For Each wnd As Window In Application.Current.Windows
If wnd.GetType Is GetType(Window1) Then
DirectCast(wnd, Window1).TextBox1.Text = "something"
End If
Next
You could probably do it just going on the Window.Name property instead of using GetType but I just prefer to do it that way.
The other option, (useful if you have more than one instance of each window at any one time) is to use your own List(Of Window) to keep track of the instances. So then when you show a new window you add it to this list and when a window closes you remove it from this list. Then when you want to access something on another window you just loop through the list and look for whatever unique ID you are using to identify each instance of the windows.
There may be better ways to do this (and I would be keen to hear them) but that is how I deal with it :)
Hope that helps