본문 바로가기

VB.net & WPF & C#

WPF Custom Window

So let us start with step by step process.

Step 1: First of all create a new WPF project and name it WpfSample

  • Open visual studio, go to File -> New -> Project
Create New Project
Create New Project

Select WPF Application and name it ‘WpfSample’

Create Wpf application
Create Wpf application

 

Step 2: Modify main window

As we want to create metro style window, first we will remove default title bar from the window and set the background color to an application. To do so, we will change the window property as mentioned below:

  • WindowStyle=”None” (Removes default TitleBar.)
  • Background=”#293857″ (sets background color of the window.)
  • BorderThickness=”0″ (Sets border thickness to zero.)
  • AllowTransparency=”True” (To allow window transparency.)

Step 3: Create Title Bar

After completion of above step, when you run the application by pressing Ctrl + F5, you will see a square window without title bar. Now its time to create our custom title bar using dock panel and in which we will put our custom buttons for Close, Restore and Minimize.

To create a title bar, we will define a grid having two rows and out of them first row will be used for TitleBar and another row will be used for the main content of the page.

Below code defines a window which looks like metro style

After writing above code, when you run your application it will look something like this:

Metro Style Window without content

Step 4: Handle Title Bar events

Till now we have created a simple window having title bar only. But buttons on title bar and drag-drop functionality are still not working. In this step we will achieve these functionalities. So first of all define the click event of buttons and MouseDown event of title as mentioned below:

  • buttonClose: Click=”buttonClose_Click”
  • buttonRestore: Click=”buttonRestore_Click”
  • buttonMinimize: Click=”buttonMinimize_Click”
  • labelApplicationTitle: MouseDown=”labelApplicationTitle_MouseDown”

So your DockPanel will finally look like this:

Now go to the code behind page MainWindow.xaml.cs and define each event as mentioned below:

Note: Please see the comments and summary tag to understand each events

After writing events as above, you are almost done. Now your window works same as a normal window and it looks like Metro style UI.