IgorShare Thoughts and Ideas

Consulting and Training

Creating custom shaped windows in WPF

Posted by Igor Moochnick on 01/08/2008

The unleashed power of WPF can do wonders, but be very carefull while creating custom shaped windows – keep the usability in mind. It should be clear to a user what each control represents and what the presented information means.

So, if you are planning to make you window cool, you have to drop the chains of the Windows themes. To do so you have to set the WindowStyle=”None”. This removed the window’s title bar, borders, control, maximize, minimize and close buttons – in simple words, EVERYTHING. This means you have to take control of the window into your hands. You have to give a user a way to close and move the window around. Don’t forget about the resize, if applicable.

To make your button close your window, you should set its Command property to ApplicationCommand.Close. If you’ll type “Close” in the Command property – Expression Blend will generate correct code for you. This is how this will look in Blend:

image

Setting the Command property will not do the all job. You need to bind the command to the actual action Window.Close() by using a CommandBinding class and assigning a new event handler. Here you can use Lambda notation to make the code simple.

   1: public partial class MainWindow
   2: {
   3:     public MainWindow()
   4:     {
   5:         this.InitializeComponent();
   6:  
   7:         // Bind the Close command to the close action
   8:         CommandBindings.Add(new CommandBinding(ApplicationCommands.Close,
   9:             new ExecutedRoutedEventHandler(( sender, args) => Close() )));
  10:  
  11:         // NOTE: for those who is not familiar with lambda expressions
  12:         // ( sender, args) => Close()   is literally equivalent to
  13:         // delegate(object sender, ExecutedRoutedEventArgs args) { this.Close(); }
  14:     }
  15:  
  16:     private void DragWindow(object sender, MouseButtonEventArgs e)
  17:     {
  18:         DragMove();
  19:     }
  20: }

To make my window draggable, I’ve associated the MouseLeftButtonDown event of the orange window corner to the DragWindow event.

You see, it’s easy. So go and experiment – unleash your imaginations.

Stay tuned for more WPF tips and tricks.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: