ShutdownMode.OnLastWindowClose


   
  


<Window x:Class="ApplicationShutdownSample.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Main Window" Height="300" Width="300" Loaded="MainWindow_Loaded">
  <StackPanel>
      <Label HorizontalAlignment="Left">Shutdown Mode:</Label>
      <ComboBox HorizontalAlignment="Left" Name="shutdownModeListBox"></ComboBox>
      <Button Click="explicitShutdownButton_Click">Shutdown Explicitly (Passing Exit Code)</Button>
  </StackPanel>
</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;

namespace ApplicationShutdownSample
{
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            this.shutdownModeListBox.Items.Add("OnLastWindowClose");
            this.shutdownModeListBox.Items.Add("OnExplicitShutdown");
            this.shutdownModeListBox.Items.Add("OnMainWindowClose");
            this.shutdownModeListBox.SelectedValue = "OnLastWindowClose";
            this.shutdownModeListBox.SelectionChanged += new SelectionChangedEventHandler(shutdownModeListBox_SelectionChanged);
            Application.Current.ShutdownMode = ShutdownMode.OnLastWindowClose;
        }

        void shutdownModeListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Application.Current.ShutdownMode = (ShutdownMode)Enum.Parse(typeof(ShutdownMode), this.shutdownModeListBox.SelectedValue.ToString());
        }


        void explicitShutdownButton_Click(object sender, RoutedEventArgs e)
        {
            int exitCode = 0;
            Application.Current.Shutdown(exitCode);
        }
    }
}

   
    
     


Custom Element Binding Window


   
  

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:src="clr-namespace:MyNameSpace.CustomElementBinding" 
        Title="Custom Element Binding Demo">
    <StackPanel>
        <ScrollBar Orientation="Horizontal"
                   Margin="24" 
                   Maximum="100"
                   LargeChange="10"
                   SmallChange="1"  
                   Value="{Binding ElementName=simple, Path=Number,Mode=OneWayToSource}" />

    <src:SimpleElement x:Name="simple" HorizontalAlignment="Center" />
    </StackPanel>
</Window>
//File:Window.xaml.cs
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Media;

namespace MyNameSpace.CustomElementBinding
{
    class SimpleElement : FrameworkElement
    {
        public static DependencyProperty NumberProperty;
        static SimpleElement()
        {
            NumberProperty = DependencyProperty.Register("Number", typeof(double),typeof(SimpleElement),
                    new FrameworkPropertyMetadata(0.0,FrameworkPropertyMetadataOptions.AffectsRender));
        }
        public double Number
        {
            set { SetValue(NumberProperty, value); }
            get { return (double)GetValue(NumberProperty); }
        }
        protected override Size MeasureOverride(Size sizeAvailable)
        {
            return new Size(200, 250);
        }
        protected override void OnRender(DrawingContext dc)    
        {
            dc.DrawText(new FormattedText(Number.ToString(), 
                        CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
                        new Typeface("Times New Roman"), 12, 
                        SystemColors.WindowTextBrush), 
                new Point(0, 0)); 
        }
    }
}

   
    
     


Use Window Activated and Deactivated event to control a media file


   
  


<Window x:Class="CustomMediaPlayerWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Custom Media Player"
    Activated="window_Activated"
    Deactivated="window_Deactivated"
    Closing="window_Closing">
  <DockPanel>
    <Menu DockPanel.Dock="Top">
      <MenuItem Header="_File">
        <MenuItem Header="_Exit" Click="exitMenu_Click" />
      </MenuItem>
    </Menu>
    <StackPanel DockPanel.Dock="Top" Orientation="Horizontal" HorizontalAlignment="Center">
      <Button Name="playButton" Click="playButton_Click">Play</Button>
      <Button Name="clickButton" Click="stopButton_Click">Stop</Button>
    </StackPanel>
    <MediaElement Stretch="Fill" Name="mediaElement" LoadedBehavior="Manual" Source="numbers.wmv" />
  </DockPanel>
</Window>
//File:Window.xaml.cs
using System;
using System.ComponentModel;
using System.Windows;

public partial class CustomMediaPlayerWindow : Window
{
    public CustomMediaPlayerWindow()
    {
        InitializeComponent();
    }

    bool isMediaElementPlaying;
    
    void playButton_Click(object sender, RoutedEventArgs e) {
        this.mediaElement.Play();
        this.isMediaElementPlaying = true;
    }

    void stopButton_Click(object sender, RoutedEventArgs e)
    {
        this.mediaElement.Stop();
        this.isMediaElementPlaying = false;
    }

    void window_Activated(object sender, EventArgs e)
    {
        if( this.isMediaElementPlaying ) this.mediaElement.Play();
    }

    void window_Deactivated(object sender, EventArgs e)
    {
        if (this.isMediaElementPlaying) this.mediaElement.Pause();
    }

    void exitMenu_Click(object sender, RoutedEventArgs e)
    {
        this.Close();
    }

    void window_Closing(object sender, CancelEventArgs e)
    {
        if (this.isMediaElementPlaying)
        {
            e.Cancel = true;
        }
    }
}

   
    
     


Order of precedence for sizing-related properties that are implemented by Window.


   
  

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="SizingPrecedenceSampleCSharp.MainWindow"
    Title="Sizing Sample" Height="300" Width="300" SizeToContent="WidthAndHeight">
  <StackPanel>
      <CheckBox Name="setWSCB" Content="Set WindowState?"/>
      <ComboBox Name="wsLB" IsEnabled="{Binding ElementName=setWSCB,Path=IsChecked}">
        <ComboBoxItem IsSelected="True">Minimized</ComboBoxItem>
        <ComboBoxItem>Maximized</ComboBoxItem>
        <ComboBoxItem>Normal</ComboBoxItem>
      </ComboBox>
      <CheckBox Name="setMinWidthCB" Content="Set MinWidth?"/>
      <TextBox Name="minWidthTB" IsEnabled="{Binding ElementName=setMinWidthCB,Path=IsChecked}">500</TextBox>
      <CheckBox Name="setMinHeightCB" Content="Set MinHeight?"/>
      <TextBox Name="minHeightTB" IsEnabled="{Binding ElementName=setMinHeightCB,Path=IsChecked}">500</TextBox>
      <CheckBox Name="setSTCCB" Content="Set SizeToContent?"/>
      <ComboBox Name="stcLB" IsEnabled="{Binding ElementName=setSTCCB,Path=IsChecked}">
        <ComboBoxItem IsSelected="True">Manual</ComboBoxItem>
        <ComboBoxItem>Width</ComboBoxItem>
        <ComboBoxItem>Height</ComboBoxItem>
        <ComboBoxItem>WidthAndHeight</ComboBoxItem>
      </ComboBox>
      <CheckBox Name="setMaxWidthCB" Content="Set MaxWidth?"></CheckBox>
      <TextBox Name="maxWidthTB" IsEnabled="{Binding ElementName=setMaxWidthCB,Path=IsChecked}">800</TextBox>
      <CheckBox Name="setMaxHeightCB" Content="Set MaxHeight?"></CheckBox>
      <TextBox Name="maxHeightTB" IsEnabled="{Binding ElementName=setMaxHeightCB,Path=IsChecked}">800</TextBox>
      <CheckBox Name="setWidthCB" Content="Set Width?"></CheckBox>
      <TextBox Name="widthTB" IsEnabled="{Binding ElementName=setWidthCB,Path=IsChecked}">700</TextBox>
      <CheckBox Name="setHeightCB" Content="Set Height?"></CheckBox>
      <TextBox Name="heightTB" IsEnabled="{Binding ElementName=setHeightCB,Path=IsChecked}">700</TextBox>
      <Button Click="showWindowButton_Click">Show Window</Button>
  </StackPanel>
</Window>

//File:Window.xaml.cs

using System;
using System.Windows;

namespace SizingPrecedenceSampleCSharp
{
    public partial class MainWindow : System.Windows.Window
    {

        public MainWindow()
        {
            InitializeComponent();
        }

        void showWindowButton_Click(object sender, RoutedEventArgs e)
        {
            MainWindow sw = new MainWindow();

            if (this.setWSCB.IsChecked == true) sw.WindowState = (WindowState)Enum.Parse(typeof(WindowState), this.wsLB.Text);
            if (this.setMinWidthCB.IsChecked == true) sw.MinWidth = double.Parse(this.minWidthTB.Text);
            if (this.setMinHeightCB.IsChecked == true) sw.MinHeight = double.Parse(this.minHeightTB.Text);
            if (this.setMaxWidthCB.IsChecked == true) sw.MaxWidth = double.Parse(this.maxWidthTB.Text);
            if (this.setMaxHeightCB.IsChecked == true) sw.MaxHeight = double.Parse(this.maxHeightTB.Text);
            if (this.setWidthCB.IsChecked == true) sw.Width = double.Parse(this.widthTB.Text);
            if (this.setHeightCB.IsChecked == true) sw.Height = double.Parse(this.heightTB.Text);
            if (this.setSTCCB.IsChecked == true) sw.SizeToContent = (SizeToContent)Enum.Parse(typeof(SizeToContent), this.stcLB.Text);

            sw.Show();
        }
    }
}

   
    
     


Create a non-rectangular window


   
  

<Window x:Class="NonRectangularWindowSample.NonRectangularWindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="NonRectangularWindowSample" SizeToContent="WidthAndHeight" 
  MouseLeftButtonDown="NonRectangularWindow_MouseLeftButtonDown"
  WindowStyle="None" 
  AllowsTransparency="True" 
  Background="Transparent">
  <Canvas Width="200" Height="200" >
    <Path Stroke="DarkGray" StrokeThickness="2">

      <Path.Fill>
        <LinearGradientBrush StartPoint="0.2,0" EndPoint="0.8,1" >
          <GradientStop Color="White"  Offset="0"></GradientStop>
          <GradientStop Color="Red"  Offset="0.45"></GradientStop>
          <GradientStop Color="LightBlue" Offset="0.9"></GradientStop>
          <GradientStop Color="Gray" Offset="1"></GradientStop>
        </LinearGradientBrush>
      </Path.Fill>

      <Path.Data>
        <PathGeometry>
          <PathFigure StartPoint="40,20" IsClosed="True">
            <LineSegment Point="160,20"></LineSegment>
            <ArcSegment Point="180,40" Size="20,20" SweepDirection="Clockwise"></ArcSegment>
            <LineSegment Point="180,80"></LineSegment>
            <ArcSegment Point="160,100" Size="20,20" SweepDirection="Clockwise"></ArcSegment>
            <LineSegment Point="90,100"></LineSegment>
            <ArcSegment Point="20,80" Size="20,20" SweepDirection="Clockwise"></ArcSegment>
            <LineSegment Point="20,40"></LineSegment>
            <ArcSegment Point="40,20" Size="20,20" SweepDirection="Clockwise"></ArcSegment>
          </PathFigure>
        </PathGeometry>
      </Path.Data>

    </Path>

    <Label Width="200" Height="120" FontSize="15" HorizontalContentAlignment="Center" VerticalContentAlignment="Center">Drag Me</Label>
    <Button Canvas.Left="155" Canvas.Top="30" Click="closeButtonRectangle_Click">
      <Button.Template>
        <ControlTemplate>
          <Canvas>
            <Rectangle Width="15" Height="15" Stroke="Black" RadiusX="3" RadiusY="3">
              <Rectangle.Fill>
                <SolidColorBrush x:Name="myAnimatedBrush" Color="Red" />
              </Rectangle.Fill>
            </Rectangle>
            <Line X1="3" Y1="3" X2="12" Y2="12" Stroke="White" StrokeThickness="2"></Line>
            <Line X1="12" Y1="3" X2="3" Y2="12" Stroke="White" StrokeThickness="2"></Line>
          </Canvas>
        </ControlTemplate>
      </Button.Template>
    </Button>
  </Canvas>
</Window>
//File:Window.xaml.cs
using System;
using System.Windows;
using System.Windows.Input;

namespace NonRectangularWindowSample {

  public partial class NonRectangularWindow : Window {

    public NonRectangularWindow() {
      InitializeComponent();
    }

    void NonRectangularWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
      this.DragMove();
    }

    void closeButtonRectangle_Click(object sender, RoutedEventArgs e) {
      this.Close();
    }
  }
}

   
    
     


Window.CommandBindings


   
  
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Class="AboutDialog"
        Title="About WPF Unleashed" SizeToContent="WidthAndHeight"
        Background="OrangeRed">
  <Window.CommandBindings>
    <CommandBinding Command="Help" CanExecute="HelpCanExecute" Executed="HelpExecuted"/>
  </Window.CommandBindings>
  <StackPanel>
    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
      <Button MinWidth="75" Margin="10" Command="Help" Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"/>
      <Button MinWidth="75" Margin="10">OK</Button>
    </StackPanel>
    <StatusBar>asdf</StatusBar>
  </StackPanel>
</Window>

//File:Window.xaml.cs

using System.Windows;
using System.Windows.Input;

public partial class AboutDialog : Window
{
    public AboutDialog()
    {
        InitializeComponent();
    }

    void HelpCanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = true;
    }
    
    void HelpExecuted(object sender, ExecutedRoutedEventArgs e)
    {
        System.Diagnostics.Process.Start("http://www.kutayzorlu.com/java2s/com");
    }
}

   
    
     


Window.DragMove


   
  


<Window x:Class="GadgetWindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Height="300" Width="300"
  AllowsTransparency="True" WindowStyle="None" Background="Transparent"
  MouseLeftButtonDown="Window_MouseLeftButtonDown">
  <Grid>
    <Ellipse Fill="Red" Opacity="0.5" Margin="20">
      <Ellipse.BitmapEffect>
        <DropShadowBitmapEffect/>
      </Ellipse.BitmapEffect>
    </Ellipse>
    <Button Margin="100" Click="Button_Click">Close</Button>
  </Grid>
</Window>
//File:Window.xaml.cs

using System.Windows;
using System.Windows.Input;

public partial class GadgetWindow : Window
{
  public GadgetWindow()
  {
    InitializeComponent();
  }
  void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
  {
    this.DragMove();
  }
  void Button_Click(object sender, RoutedEventArgs e)
  {
      this.Close();
  }
}