By now, you should be aware that I’m a big fan of attached behaviors. In this post, I’m going to demonstrate a simple technique to add resize and close functionality to window buttons when you want to custom draw your window chrome without having to add code behind the window. This is going to be a quick post, because it’s just so darned easy.
namespace AttachedTitleButtonsSample
{
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
public partial class TitleButtonBehavior : Behavior<Button>
{
public enum TitleButtonAction
{
Close,
Maximize,
Minimize,
Normal
}
public TitleButtonAction ButtonBehavior { get; set; }
protected override void OnAttached()
{
this.AssociatedObject.Click += AssociatedObject_Click;
base.OnAttached();
}
protected override void OnDetaching()
{
this.AssociatedObject.Click += AssociatedObject_Click;
base.OnDetaching();
}
void AssociatedObject_Click(object sender, System.Windows.RoutedEventArgs e)
{
switch (ButtonBehavior)
{
case TitleButtonAction.Close:
Application.Current.MainWindow.Close();
break;
case TitleButtonAction.Maximize:
Application.Current.MainWindow.WindowState = WindowState.Maximized;
break;
case TitleButtonAction.Minimize:
Application.Current.MainWindow.WindowState = WindowState.Minimized;
break;
case TitleButtonAction.Normal:
Application.Current.MainWindow.WindowState = WindowState.Normal;
break;
}
}
}
}
Basically, all you need to do is create an attached behavior that hooks up to the Click
event of the button and sets the size based on the appropriate value from the enumeration.
Sample Application
I’ve attached a sample application that demonstrates this technique in action. As always, when you download the sample, you’ll need to rename it from a doc to a zip file.
A developer for over 30 years, I've been lucky enough to write articles and applications for Code Project as well as the Intel Ultimate Coder - Going Perceptual challenge. I live in the North East of England with 2 wonderful daughters and a wonderful wife.
I am not the Stig, but I do wish I had Lotus Tuned Suspension.