|
-
Jul 15th, 2009, 05:26 AM
#3
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
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|