Articles
This behavior brings you the possibilities to let a command called if a window is loaded, closing or closed. The closing can be canceled by an additional parameter. Furthermore it is possible to let the DialogResult set by a button or ask a command how to set the DialogResult. It is usefully especially for MVVM applications.

Usage
<Window x:Class="DW.Interactivity.Demo.DemoWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Interactivity="http://schemas.my-libraries.de/wpf/interactivity"
Interactivity:WindowBehavior.LoadedCommand="{Binding LoadedCommand}"
Interactivity:WindowBehavior.ClosingCommand="{Binding ClosingCommand}"
Interactivity:WindowBehavior.WinApiMessages="0x216;0x214"
Interactivity:WindowBehavior.WinApiCommand="{Binding WinApiCommand}"
Title="DemoWindow"
Height="300"
Width="300">
<DockPanel>
<StackPanel DockPanel.Dock="Top" HorizontalAlignment="Center">
<GroupBox Header="Modal Window">
<StackPanel>
<Button Content="Close as OK" Interactivity:WindowBehavior.DialogResult="True" />
<Button Content="Close as Cancel" Interactivity:WindowBehavior.DialogResult="False" />
<Button Content="Close with Command" Interactivity:WindowBehavior.DialogResultCommand="{Binding ClosingCommand}" />
</StackPanel>
</GroupBox>
<GroupBox Header="Non-Modal Window">
<Button Content="Close" Interactivity:WindowBehavior.IsClose="True" />
</GroupBox>
</StackPanel>
<ListBox ItemsSource="{Binding Items}" />
</DockPanel>
</Window>
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Input;
using DW.SharpTools;
namespace DW.Interactivity.Demo
{
public partial class DemoWindow : Window
{
public DemoWindow()
{
InitializeComponent();
DataContext = this;
Items = new ObservableCollection<string>();
LoadedCommand = new DelegateCommand(p => WindowLoaded());
ClosingCommand = new DelegateCommand(WindowClosing);
WinApiCommand = new DelegateCommand(WinApi);
}
public ICommand LoadedCommand { get; set; }
private void WindowLoaded()
{
MessageBox.Show(this, "Loaded");
}
public ICommand ClosingCommand { get; set; }
private void WindowClosing(object arg)
{
var e = (WindowClosingArgs)arg;
if (MessageBox.Show(this, "Close?", "Demo", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
e.Cancel = true;
}
public ICommand WinApiCommand { get; set; }
public ObservableCollection<string> Items { get; set; }
private int _moveCount = 1;
private int _sizeCount = 1;
private void WinApi(object arg)
{
var e = (NotifyEventArgs)arg;
if (e.MessageId == WindowMessages.WM_MOVING)
Items.Insert(0, string.Format("{0} WM_MOVING", _moveCount++));
else if (e.MessageId == WindowMessages.WM_SIZING)
Items.Insert(0, string.Format("{0} WM_SIZING", _sizeCount++));
}
}
}
Note
This control needs the DW.SharpTools.