#1,105 – Using Application’s Windows Collection to Interact with Other Windows

You can use the Application object’s Windows property to get a list of all active windows.  If you then cast to your specific subclass of Window, you can interact with the various child windows.

Suppose that we have a main window with a button for creating other windows.

        private void btnCreate_Click(object sender, RoutedEventArgs e)
        {
            OtherWindow ow = new OtherWindow();
            ow.Show();
        }

Assume that the child windows have a TextBox that binds to a property in the code-behind.

        <TextBox Text="{Binding SomeText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                 Margin="10" Height="25"/>

The code-behind would look like this:

    public partial class OtherWindow : Window, INotifyPropertyChanged
    {
        public OtherWindow()
        {
            InitializeComponent();
            this.DataContext = this;
        }

        private string someText;
        public string SomeText
        {
            get { return someText; }
            set
            {
                someText = value;
                RaisePropChanged("SomeText");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        private void RaisePropChanged(string prop)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(prop));
        }
    }

We can now get information on all child windows as shown below (this is an event handler for another button on the main window).

        private void btnList_Click(object sender, RoutedEventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            foreach (Window w in Application.Current.Windows)
            {
                OtherWindow ow = w as OtherWindow;
                if (ow != null)
                    sb.AppendLine(ow.SomeText);
            }

            MessageBox.Show(sb.ToString());
        }

1105-001

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #1,105 – Using Application’s Windows Collection to Interact with Other Windows

  1. Pingback: Dew Drop – July 2, 2014 (#1806) | Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: