You see, you don’t always need code behind.
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;
/// <summary>
/// Attach this behaviour to a button to enable a button
/// to change the window state without
/// having to write any code behind the view.
/// </summary>
public partial class TitleButtonBehavior : Behavior<Button>
{
/// <summary>
/// The tile button action to apply.
/// </summary>
public enum TitleButtonAction
{
/// <summary>
/// Close the application
/// </summary>
Close,
/// <summary>
/// Maximize the application
/// </summary>
Maximize,
/// <summary>
/// Minimize the application
/// </summary>
Minimize,
/// <summary>
/// Reset the application to normal
/// </summary>
Normal
}
/// <summary>
/// Gets or sets the button behavior.
/// </summary>
public TitleButtonAction ButtonBehavior { get; set; }
/// <summary>
/// Add the click handler when this is attached.
/// </summary>
protected override void OnAttached()
{
this.AssociatedObject.Click += AssociatedObject_Click;
base.OnAttached();
}
/// <summary>
/// Remove the click handler when this is detached.
/// </summary>
protected override void OnDetaching()
{
this.AssociatedObject.Click += AssociatedObject_Click;
base.OnDetaching();
}
/// <summary>
/// Change the window state when the button is clicked.
/// </summary>
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.

发表评论
SRrVfP Wow, great blog article.Really thank you! Great.
CZMR2F Really enjoyed this article post.Much thanks again. Really Cool.