#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