Activate window, close window, bring window to front


   
  

<Window x:Class="WpfApplication1.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:system="clr-namespace:System.Windows;assembly=PresentationFramework"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="Main Window" Height="310" Width="280" Loaded="Window1_Loaded">
  <Window.Resources>
    <DataTemplate DataType="{x:Type Window}" x:Key="WindowTemplate">
      <StackPanel>
        <Rectangle Height="50" Width="50">
          <Rectangle.Fill>
            <VisualBrush Visual="{Binding}" />
          </Rectangle.Fill>
        </Rectangle>
        <TextBlock Text="{Binding Path=Title}" />
      </StackPanel>
    </DataTemplate>
  </Window.Resources>
  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="100" />
      <RowDefinition Height="*" />
    </Grid.RowDefinitions>

    <ListBox x:Name="lbxWindows" ItemTemplate="{StaticResource WindowTemplate}">
      <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
          <WrapPanel />
        </ItemsPanelTemplate>
      </ListBox.ItemsPanel>
    </ListBox>

    <StackPanel Grid.Row="1">
      <CheckBox x:Name="cbxIsVisibleInTaskBar" Content="IsVisibleInTaskbar" IsChecked="{Binding ElementName=lbxWindows, Path=SelectedItem.ShowInTaskbar}"/>
      <CheckBox x:Name="cbxIsVisible" Content="IsVisible" 
      IsChecked="{Binding ElementName=lbxWindows, Path=SelectedItem.IsVisible, Mode=OneWay}" 
      Checked="CheckBox_Checked_Changed" 
        Unchecked="CheckBox_Checked_Changed"/>
      <CheckBox x:Name="cbxCanClose" Content="CanClose" IsChecked="True"/>
      <Button Content="Bring To Front" Click="btnBringToFront_Click" />
      <Button Content="Close" Click="btnClose_Click"/>
    </StackPanel>
  </Grid>
</Window>
//File:Window.xaml.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;

namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void Window1_Loaded(object sender, RoutedEventArgs e)
        {
            for (int i = 1; i <= 5; i++)
            {
                Window window = new Window();

                SetupWindow(window, "Window " + i);

                window.Show();
            }
            
            RebuildWindowList();
        }
        private void SetupWindow(Window window, string title)
        {
            window.Closing += new CancelEventHandler(Window_Closing);
            window.Closed += new EventHandler(Window_Closed);
            window.Title = title;
            window.Width = 100d;
            window.Height = 100d;
            window.Content = title;
        }
        private void RebuildWindowList()
        {
            List<Window> windows = new List<Window>();

            foreach (Window window in Application.Current.Windows)
            {
                if (window == this)
                    continue;

                windows.Add(window);
            }

            lbxWindows.ItemsSource = windows;
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            RebuildWindowList();
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            Window w = sender as Window;

            if (w == null)
                return;

            e.Cancel = !cbxCanClose.IsChecked == true;
        }

        private void CheckBox_Checked_Changed(object sender, RoutedEventArgs e)
        {
            Window window = lbxWindows.SelectedItem as Window;

            if (window == null) 
                return;

            if (cbxIsVisible.IsChecked == true)
                window.Show();
            else
                window.Hide();
        }

        private void btnBringToFront_Click(object sender, RoutedEventArgs e)
        {
            Window window = lbxWindows.SelectedItem as Window;

            if (window != null)
                window.Activate();
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            Window window = lbxWindows.SelectedItem as Window;

            if (window != null)
                window.Close();
        }
    }
}

   
    
     


Create Window and add window closing event handler


//File:Window.xaml.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;

namespace WpfApplication1
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void Window1_Loaded(object sender, RoutedEventArgs e)
{
Brush[] backgrounds = new Brush[5]{ Brushes.Red,
Brushes.Blue,
Brushes.Green,
Brushes.Yellow,
Brushes.HotPink};
for (int i = 1; i <= 5; i++) { Window window = new Window(); SetupWindow(window, "Window " + i, backgrounds[i - 1]); window.Show(); } } private void SetupWindow(Window window, string title, Brush background) { window.Closing += new CancelEventHandler(Window_Closing); window.Closed += new EventHandler(Window_Closed); window.Title = title; window.Width = 100d; window.Height = 100d; Viewbox viewBox = new Viewbox(); TextBlock textBlock = new TextBlock(); window.Background = background; viewBox.Child = textBlock; textBlock.Text = window.Title; window.Content = viewBox; } private void Window_Closed(object sender, EventArgs e) { Console.WriteLine("closed"); } private void Window_Closing(object sender, CancelEventArgs e) { Window w = sender as Window; if (w == null) return; } } } [/csharp]

Listen to Window loaded event


   
  

<Window x:Class="WpfApplication1.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title=" " Height="300" Width="300" Loaded="Window1_Loaded">
  <Grid>
    <Viewbox>
      <TextBox x:Name="tbxEditMe" Text="Edit Me..." />
    </Viewbox>      
  </Grid>
</Window>


//File:Window.xaml.cs
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void Window1_Loaded(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("", "loaded");
            
        }
    }
}

   
    
     


Show window based on button name


   
  
<Window x:Class="LayoutPanels.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Menu" Height="375.2" Width="252">
    <Grid>
      <StackPanel Margin="5" Button.Click="ButtonClick">
        <Button>SimpleStack</Button>
        <Button>SimpleWrap</Button>
        <Button>SimpleDock</Button>
        <Button>BasicDialogBox</Button>
        <Button>SimpleGrid</Button>
        <Button>SplitWindow</Button>
        <Button>DoubleSplitWindow</Button>
        <Button>SharedSizeGroup</Button>
        <Button>SimpleCanvas</Button>
        <Button>SimpleInkCanvas</Button>
        <Button>TheUniformGrid</Button>
        <Button>TextBoxColumn</Button>
        <Button>LocalizableText</Button>
        <Button>ModularContent</Button>
      </StackPanel>
        
    </Grid>
</Window>

//File:Window.xaml.cs

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Reflection;


namespace LayoutPanels
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void ButtonClick(object sender, RoutedEventArgs e)
        {
            Button cmd = (Button)e.OriginalSource;
                
            Type type = this.GetType();
            Assembly assembly = type.Assembly;                       
            Window win = (Window)assembly.CreateInstance("YourNameSpace." + cmd.Content);

            win.ShowDialog();
        }
    }
}

   
    
     


Change window cursor


   
  

<Window x:Class="EightBall.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Eight Ball Answer" Height="328" Width="412" >
  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="*" />
      <RowDefinition Height="Auto" />
      <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.Background>
      <LinearGradientBrush>
        <LinearGradientBrush.GradientStops>
          <GradientStop Offset="0.00"  Color="Red" />
          <GradientStop Offset="0.50" Color="Indigo" />
          <GradientStop Offset="1.00" Color="Violet" />
        </LinearGradientBrush.GradientStops>
      </LinearGradientBrush>
    </Grid.Background>
    <TextBox VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Margin="10,10,13,10" Name="txtQuestion" 
             TextWrapping="Wrap" FontFamily="Verdana" FontSize="24"
             Grid.Row="0" >
      text
    </TextBox>
    <Button VerticalAlignment="Top" HorizontalAlignment="Left" Margin="10,0,0,20" Width="127" Height="23" Name="cmdAnswer"
            Click="cmdAnswer_Click" 
            Grid.Row="1">      
      Click
      </Button>
    <TextBox VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Margin="10,10,13,10" Name="txtAnswer" 
             TextWrapping="Wrap" IsReadOnly="True" FontFamily="Verdana" FontSize="24" Foreground="Green"
             Grid.Row="2">
      text
    </TextBox>    
  </Grid>
</Window>

//File:Window.xaml.cs

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Input;

namespace EightBall
{
    public partial class Window1 : Window
    {

        public Window1()
        {
            InitializeComponent();
        }

        private void cmdAnswer_Click(object sender, RoutedEventArgs e)
        {           
            this.Cursor = Cursors.Wait;
            System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1));

            txtAnswer.Text = "asdf";
            this.Cursor = null;
        }

    }
}

   
    
     


Load the Data for a Window Asynchronously After It Has Rendered



One Million Numbers:




//File:Window.xaml.cs
using System.Windows;
using System.Windows.Threading;
using System.Collections.Generic;

namespace WpfApplication1
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();

}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.Dispatcher.BeginInvoke(DispatcherPriority.Background,new LoadNumbersDelegate(LoadNumbers));
}
private delegate void LoadNumbersDelegate();
private void LoadNumbers()
{
List numberDescriptions = new List();
for(int i = 1; i <= 1000000; i++) { numberDescriptions.Add("Number " + i.ToString()); } listBox.ItemsSource = numberDescriptions; } } } [/csharp]

Is Window active


   
  


<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="AppWindowsSample" Height="200" Width="300" 
    xmlns:my="clr-namespace:System;assembly=mscorlib">
  <StackPanel>
    <Menu Name="menu1" >
      <MenuItem Header="Window" x:Name="windowMenu">
        <MenuItem Header="SubmenuOpened event" />
      </MenuItem>
    </Menu>
    <Button Margin="10" Name="newWindowButton" Height="23" VerticalAlignment="Top">New Window</Button>
    <StatusBar Grid.Row="2" Name="statusBar1" >
      <TextBlock x:Name="statusText">Status</TextBlock>
    </StatusBar>
    <Button Height="23" Margin="10" Name="shutdownButton" VerticalAlignment="Top" >Shutdown</Button>
  </StackPanel>
</Window>
//File:Window.xaml.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;
using System.Diagnostics;
using System.ComponentModel;


namespace WpfApplication1 {
  public partial class Window1 : System.Windows.Window {

    public Window1() {
      InitializeComponent();

      DataContext = Application.Current.Windows;
      statusText.Text = Application.Current.ShutdownMode.ToString();

      newWindowButton.Click += new RoutedEventHandler(newWindowButton_Click);
      shutdownButton.Click += new RoutedEventHandler(shutdownButton_Click);
      windowMenu.SubmenuOpened += new RoutedEventHandler(windowMenu_SubmenuOpened);
      Closing += Window1_Closing;
    }

    public void windowMenu_SubmenuOpened(object sender, RoutedEventArgs e) {
      windowMenu.Items.Clear();
      foreach( Window window in Application.Current.Windows ) {
        MenuItem item = new MenuItem();
        item.Header = window.Title;
        item.Click += windowMenuItem_Click;
        item.Tag = window;
        item.IsChecked = window.IsActive;
        windowMenu.Items.Add(item);
      }
    }

    public void windowMenuItem_Click(object sender, RoutedEventArgs e) {
      Window window = (Window)((MenuItem)sender).Tag;
      window.Activate();
    }

    public void newWindowButton_Click(object sender, RoutedEventArgs e) {
      Window window = new Window();
      window.Title = "Window " + DateTime.Now;
      window.Width = 200;
      window.Height = 100;
      window.Show();
      statusText.Text = Application.Current.ShutdownMode.ToString();
    }

    void shutdownButton_Click(object sender, RoutedEventArgs e) {
      Application.Current.Shutdown();
    }

    void Window1_Closing(object sender, CancelEventArgs e) {
      if( MessageBox.Show("Do you really want to shut down?", "Shutting Down", MessageBoxButton.YesNo) == MessageBoxResult.No ) {
        e.Cancel = true;
      }
    }


  }
}