2024年4月27日发(作者:)

Create a Login

Window in WPF

Most business applications require some sort of security system. You can always

use Windows Authentication to authenticate a user, but sometimes you might want

your own authentication scheme. When you do, you will need to create a login

screen for your user to enter her login id and password. This article will explore

creating a login window in WPF.

The UI for your login screen can contain any images and controls that you would

like. In Figure 1 you can see a sample login screen that has an image of a key, a

large title label across the top, two labels, a text box, a password box and two

button controls. You can also make the border of the window rounded so that there

is no close, minimize or maximize button and no title bar.

Figure 1: A Login Screen ()

Of course this is just one version of a login screen but let’s take a look at how this

is put together.

Create a Login Window in WPF

Creating the Window

To start, you need to create a window with no border and can be made into any

shape you want. To do this you will set a few different attributes. The WindowStyle

attribute normally allows you to set a single border, three-D border, or a Tool

Window border. Setting this attribute to None will eliminate the border. The

ShowInTaskbar attribute is optional, but if you are building a login screen you

probably won’t want this window to show up in the Task Bar as it is going to be

modal style form. The next two attributes, AllowsTransparency and Background

work together. You must set AllowsTransparency to True to allow the Background

to be set to Transparent. If you do not set these two attributes, then your border will

still show up. Below is the xaml for this window.

WindowStartupLocation="CenterScreen"

AllowsTransparency="True"

ShowInTaskBar=False

Background="Transparent"

WindowStyle="None"

SizeToContent="WidthAndHeight"

dElement=

"{Binding ElementName=txtUserName}">

...

...

There are three additional attributes that are set on this window. The

WindowStartupLocation attribute is set to “CenterScreen” to ensure that the login

screen is displayed in the middle of the screen when it is shown. You also set the

SizeToContent attribute to WidthAndHeight to just take as much room for this

window as the controls need that are contained within this window. The

dElement attribute is data-bound to the textbox control next

to the User Name label. This tells WPF to place the cursor in this textbox once the

screen is displayed.

The Border

Now that you have the Window xaml defined you now can create the look for the

outside border of the window. A Border control is used to form the outside of this

login screen. You will set the CornerRadius attribute to “10” to give the nice

rounded corners. You can set the BorderBrush to “Gray” and the BorderThickness

to “3”. You also want to give this border a nice wide Margin to allow room for the

2 Create a Login Window in WPF

Copyright © 2009 by PDSA, Inc.

All rights reserved. Reproduction is strictly prohibited.

Using a Grid Layout

DropShadowEffect that we add to the outside of this border. If you do not do this,

then the drop shadow will be chopped off. To achieve the shadow effect on this

window, you will use the new and the DropShadowEffect that was

added in WPF 3.5. This drop shadow effect is drawn using the Graphical

Processing Unit (GPU) instead of being drawn using software. Thus drawing drop

shadows is much more performant than in previous versions of WPF.

BorderBrush="Gray"

BorderThickness="3"

Background="Beige"

Margin="24"

Padding="4">

<>

Opacity=".50"

ShadowDepth="16" />

...

...

Using a Grid Layout

To place each of the login screen elements within the border, a Grid control is used

with specific column and row definitions. There are three columns in this login

screen. One for the image of the key, one for the labels and one for the TextBox,

PasswordBox and Button controls.

Create a Login Window in WPF

Copyright © 2009 by PDSA, Inc.

All rights reserved. Reproduction is strictly prohibited.

3

Create a Login Window in WPF

...

...

Placing the Key Image

The Key image that is in the upper left hand corner of this login screen is placed

there by using a StackPanel control and an Image control. The StackPanel gives

us just a little more control over the placement within the Grid. Notice the

, and n attributes that are set on the

StackPanel. The and specify in which row and column of

the grid you wish to display the StackPanel. The n allows the key to

float down over the next three rows of the Grid control. If you were to use a smaller

or larger key image, then you would probably need to adjust this attribute

accordingly. The Image control sets the source of its image to the file

located in the /Images folder. A drop shadow effect is applied to this image control

just like you did with the Border control.

4 Create a Login Window in WPF

Copyright © 2009 by PDSA, Inc.

All rights reserved. Reproduction is strictly prohibited.

The Large Title Label

="0"

n="3">

Margin="8"

Source="/Images/">

<>

Opacity=".50"

ShadowDepth="8" />

The Large Title Label

The large label across the top of the login screen is simply a Label control with the

appropriate , and Span attributes set for

placement. A FontSize of 18 is applied to make the text appear larger than the

other labels on this screen. A Margin of 10 is used to give us some spacing from

the border of the grid.

="0"

Span="2"

FontSize="18"

Margin="10">Please Login To Access This Application

The Login Data Controls

The controls that gather the user name and password should be fairly familiar to

you if you have been doing any WPF at all. Each control is placed into a specific

row and column of the Grid control. Notice the use of the Tooltip attribute on the

TextBox and the PasswordBox control. This gives the user an idea of what to put

into each control if they hover their mouse over that control.

Create a Login Window in WPF

Copyright © 2009 by PDSA, Inc.

All rights reserved. Reproduction is strictly prohibited.

5

Create a Login Window in WPF

="1">User Name

="1"

ToolTip="Enter Your User Name"

Name="txtUserName" />

="2">Password

="2"

ToolTip="Enter Your Password"

Name="txtPassword" />

The Buttons

The two buttons at the bottom of the screen are placed into the last row of the Grid

control and into the second column of the grid by wrapping them into a StackPanel.

The StackPanel has its HorizontalAlignment attribute set to Center and it’s

Orientation attribute to Horizontal to allow the buttons to be centered within the

StackPanel and to have the buttons appear side-by-side to each other.

6 Create a Login Window in WPF

Copyright © 2009 by PDSA, Inc.

All rights reserved. Reproduction is strictly prohibited.

Writing the Code for the Login Screen

="3"

Margin="10"

HorizontalAlignment="Center"

Orientation="Horizontal">

There are two special attributes that are set on these buttons. The IsCancel

attribute is set to true on the Cancel button. Setting this attribute to true will fire the

click event procedure on the Cancel button if the user presses the Escape key. The

IsDefault attribute is set to true on the on the Login button. Setting this attribute to

true will fire the click event procedure on the Login button if the user presses the

Enter key.

Writing the Code for the Login Screen

In each of the click event procedures you will need to close the screen. In the

Cancel click event procedure you will set the DialogResult property of the screen to

a false value. This will inform the calling procedure that the user clicked on the

Cancel button on this screen. In the Login click event procedure you will set the

DialogResult property of the screen to a true value. This informs the calling

procedure that the user clicked on the Login button and was authenticated. I am

leaving it up to you to write the code for authenticating the user. Here is the code

for the Cancel event procedure.

Create a Login Window in WPF

Copyright © 2009 by PDSA, Inc.

All rights reserved. Reproduction is strictly prohibited.

7

Create a Login Window in WPF

C#

private void btnCancel_Click(object sender, RoutedEventArgs e)

{

DialogResult = false;

();

}

Visual Basic

Private Sub btnCancel_Click(ByVal sender As , _

ByVal e As EventArgs)

DialogResult = False

()

End Sub

And, here is the code for the Login event procedure.

C#

private void btnLogin_Click(object sender, RoutedEventArgs e)

{

// Write code here to authenticate user

// If authenticated, then set DialogResult=true

DialogResult = true;

();

}

Visual Basic

Private Sub btnLogin_Click(ByVal sender As , _

ByVal e As EventArgs)

DialogResult = True

()

End Sub

Displaying the Login Screen

At some point when your application launches, you will need to display your login

screen modally. Below is the code that you would call to display the login form

(named frmLogin in my sample application). This code is called from the main

application form, and thus the owner of the login screen is set to “this”. You then

call the ShowDialog method on the login screen to have this form displayed

modally. After the user clicks on one of the two buttons you need to check to see

what the DialogResult property was set to. The DialogResult property is a nullable

type and thus you first need to check to see if the value has been set.

8 Create a Login Window in WPF

Copyright © 2009 by PDSA, Inc.

All rights reserved. Reproduction is strictly prohibited.

Displaying the Login Screen

C#

private void DisplayLoginScreen()

{

frmLogin frm = new frmLogin();

= this;

alog();

if (ue && )

("User Logged In");

else

();

}

Visual Basic

Private Sub DisplayLoginScreen()

Dim frm As New frmLogin()

= Me

alog()

If ue And Then

("User Logged In")

Else

()

End If

End Sub

Create a Login Window in WPF

Copyright © 2009 by PDSA, Inc.

All rights reserved. Reproduction is strictly prohibited.

9

Create a Login Window in WPF

Summary

Creating a nice looking login screen is fairly simple to do in WPF. Using the

DropShadowEffect can add a nice finished look to not only your form, but images

and buttons as well. Using a border-less window is a great way to give a custom

look to a login screen or splash screen. The DialogResult property on WPF

Windows allows you to communicate back to the calling routine what happened on

the modal screen. I hope this article gave you some ideas on how to create a login

screen in WPF.

10 Create a Login Window in WPF

Copyright © 2009 by PDSA, Inc.

All rights reserved. Reproduction is strictly prohibited.