Hi All,
I will be giving 4 hours of real-world training on WPF this Wednesday (Nov. 18th, 2009). If you are new to WPF and wanting to learn how to use WPF to create business applications, this is a great place to start. The cost for this seminar is only $99. You can sign up at http://www.pdsa.com/learning.
I hope to see you there!
Paul D. Sheriff
If anyone is at PDC this week, I will be moderating a session on Exception Management. If you would like to discuss this topic with your other peers at PDC, please stop by!
Hope to see you there!
Paul
WPF has the flexibility to modify the look of your controls dynamically at runtime with just a few lines of code. Take a look at Figures 1 and 2 and you will see two different views of the same list box and data. To accomplish this, you simply need to setup two different resources of XAML code that you can switch between at runtime.
Figure 1: More detail

Figure 2: Less detail
The Basic Form and the Data
This XAML form uses an XML file to fill in the ListBox control with the product data. There is a folder called \Images where the pictures for the various products are located. Below is a fragment of the XML file that contains the product data.
<Products>
<Product>
<ProductId>1</ProductId>
<ProductName>PDSA .NET Productivity Framework</ProductName>
<Price>5000</Price>
<Logo>/Images/Framework.gif</Logo>
</Product>
...
...
</Products>
An XmlDataProvider control is used to load this file and supply the data for the list box. The XAML code shown below is the setup of this XmlDataProvider. This XmlDataProvider is located within the Window.Resources section of this WPF Window.
<XmlDataProvider x:Key="xProducts"
Source="/Product.xml"
XPath="Products/Product" />
As you can see in the above code the Product.xml file is located in the root of the project. You use the XPath attribute to read to the node level where the actual data is within the XML file. Then you will be able to specify the element name of where the data is for displaying in the list box.
Create the XAML Templates
The next items in the Window.Resources section of this WPF Window are the <DataTemplates>. There are two data templates created as resources in this window. One has a key of “tmplMore” and one has a key of “tmplLess”. Below is the XAML code that is used to create the list box that looks like Figure 1. You can see the use of a Horizontal StackPanel control, and an Image control as the first control within that StackPanel.
<DataTemplate x:Key="tmplMore">
<StackPanel Orientation="Horizontal">
<Image Margin="8"
Source="{Binding XPath=Logo}"
Width="100"></Image>
<Label Width="250"
Content="{Binding XPath=ProductName}"></Label>
<Label Width="100"
Content="{Binding XPath=Price}"></Label>
</StackPanel>
</DataTemplate>
Notice the data binding of the Source property of the image and the Content properties of the two labels. The Binding uses XPath attribute to signify the name of the element within the XML file. Remember that the XmlDataProvider has the first part of the XPath query, while each Binding is the element where the data is located that will be displayed in the list box.
The next data template created within the Window.Resources section has the key of “tmplLess” and looks like the XAML below. You can see that the Image control is missing from this template.
<DataTemplate x:Key="tmplLess">
<StackPanel Orientation="Horizontal">
<Label Width="250"
Content="{Binding XPath=ProductName}"></Label>
<Label Width="100"
Content="{Binding XPath=Price}"></Label>
</StackPanel>
</DataTemplate>
In the WPF Window is the definition of the list box control shown in the XAML listing below. Notice that the ItemsSource attribute is set to bind to the xProducts XmlDataProvider control. Also notice that the ItemTemplate is bound to the “tmplMore” data template resource. This is the default data template that is used when the window is first displayed.
<ListBox Margin="10,10,0,0"
Height="300"
Name="lstData"
ItemsSource="{Binding Source={StaticResource xProducts}}"
IsSynchronizedWithCurrentItem="True"
ItemTemplate="{StaticResource tmplMore}">
</ListBox>
Switch Between the XAML Templates
You will write code in each button’s click event procedures, shown below, to switch between the two XAML templates. In each event procedure you create a variable to refer to a DataTemplate object. You then use the FindResource method of the current window to find the resource named either “tmplMore” or “tmplLess”. Once you have the data template object you can assign that to the ItemTemplate property of the list box control.
One thing to note is that you should include error handling within this code because if the FindResource method does not find the resource, then it will throw an exception. I purposely left out the code for brevity in this example.
Visual Basic
Private Sub btnMore_Click(ByVal sender As System.Object, _
ByVal e As System.Windows.RoutedEventArgs) Handles btnMore.Click
Dim tmpl As DataTemplate
tmpl = DirectCast(Me.FindResource("tmplMore"), DataTemplate)
lstData.ItemTemplate = tmpl
End Sub
Private Sub btnLess_Click(ByVal sender As System.Object, _
ByVal e As System.Windows.RoutedEventArgs) Handles btnLess.Click
Dim tmpl As DataTemplate
tmpl = DirectCast(Me.FindResource("tmplLess"), DataTemplate)
lstData.ItemTemplate = tmpl
End Sub
C#
private void btnMore_Click(object sender, RoutedEventArgs e)
{
DataTemplate tmpl;
tmpl = (DataTemplate)this.FindResource("tmplMore");
lstData.ItemTemplate = tmpl;
}
private void btnLess_Click(object sender, RoutedEventArgs e)
{
DataTemplate tmpl;
tmpl = (DataTemplate)this.FindResource("tmplLess");
lstData.ItemTemplate = tmpl;
}
Summary
In this article you learned to change templates on a list box control dynamically at runtime using the FindResource method. You simply need to create a couple of XAML templates that you will use to switch between the different views. You create these XAML templates in the Window.Resources section of the window. You give each template a unique name, and then write a little code to find each of the resources at runtime. Once you have located the appropriate resource, you assign it to the ItemTemplate property of the list box and WPF will change the look of the control instantly.
NOTE: You can download the complete sample code at my website. http://www.pdsa.com/downloads. Choose Tips & Tricks, then "WPF Change Templates" from the drop-down.
Good Luck With Your Coding,
Paul Sheriff
** SPECIAL OFFER FOR MY BLOG READERS **
Visit http://www.pdsa.com/Event/Blog for a free eBook on "Fundamentals of N-Tier".
Unlike Windows Forms, there is no Visual Inheritance in WPF. Luckily you don’t need visual inheritance as you can use User Controls to get a re-usable UI. There are times, however, when you want a base Window class so you can have common functionality in all your WPF windows. To accomplish this you can create a base class from which all your WPF windows can inherit. To use the base class you will need to make one simple change in both the XAML and in your code-behind class.
<Window> Element and Window Class
When you add a new Window to a WPF application it builds a .XAML file and a code-behind file. The XAML file has a <Window> element and the code-behind file has a partial class that inherits from “Window” or “System.Windows.Window” to be more specific. Notice the x:Class=”<Namespace>.<ClassName>” syntax in the XAML (See Figure 1). This x:Class name attribute must have the same name as the partial class in the code-behind. At compile time, the .XAML file is converted into a partial class that has the same name as the name of the class in the code-behind and inherits from the name of the top level element in the XAML; in this case “Window”.

Figure 1: The Window class and the inherited Window must match.
As long as these two items match the two elements in the partial class in the code-behind the compiler will be happy. If either of these two elements does not match, you will receive a compiler error.
Inherit from the Window Class
Now that you understand the basics of how the XAML and the code-behind are put together, you can now create a base Window class and modify the XAML and code-behind to use this new class.
If you wish to follow along with this article, create a new WPF application in Visual Studio. Add a new class to your project named WindowBase. Modify this newly added class to inherit from the Window class. Add the following Imports/using statements at the top of the WindowBase class.
C#
using System.Windows;
Visual Basic
Imports System.Windows
The WindowBase class needs to inherit from the Window class by changing the code to look like the following:
C#
using System;
using System.Windows;
namespace WpfApplication1
{
public class WindowBase : Window
{
}
}
Visual Basic
Imports System.Windows
Public Class WindowBase
Inherits Window
End Class
Modify the code-behind of the Window1.xaml file to inherit from the WindowBase class you just created. Your Window1 code-behind should now look like the following:
C#
public partial class Window1 : WindowBase
{
public Window1()
{
InitializeComponent();
}
}
Visual Basic
Class Window1
Inherits WindowBase
End Class
If you were to compile the WPF application right now, you will receive the error message “Base class 'System.Windows.Window' specified for class 'Window1' cannot be different from the base class 'WindowBase' of one of its other partial types.” The reason is because while you changed the code behind to inherit from the WindowBase class, you need to change the XAML markup to reflect this same change.
The change you need to make is you need to modify the <Window> element to be <WindowBase>. However, <WindowBase> is not a part of any of the imported xml namespaces that are a normal part of the XAML markup. Thus, you need to add a namespace reference to the assembly that contains the WindowBase class. If you created a default WPF application project, the namespace you will add to the XAML is the following:
xmlns:src="clr-namespace:WpfApplication1"
Once you have added this namespace with the prefix of “src” you can now change the <Window> element to <src:WindowBase>. Be sure you modify the closing </Window> element to </src:WindowBase>. The complete source code for the XAML is shown below.
C#
<src:WindowBase
x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:WpfApplication1"
Title="Window1" Height="300" Width="300">
<Grid></Grid>
</src:WindowBase>
Visual Basic
<src:WindowBase
x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:WpfApplication1"
Title="Window1" Height="300" Width="300">
<Grid></Grid>
</src:WindowBase>
At this point you should be able to compile the application and everything should compile correctly.
Adding Functionality
Now that you have a base Window class you can add code to that class that can be used in all of your WPF Windows. Once piece of functionality you might need is to check if your Window is in design mode or runtime. Add the following property to your WindowBase class.
C#
public bool IsInDesignMode
{
get
{
return System.ComponentModel.
DesignerProperties.GetIsInDesignMode(this);
}
}
Visual Basic
Public ReadOnly Property IsInDesignMode() As Boolean
Get
Return System.ComponentModel. _
DesignerProperties.GetIsInDesignMode(Me)
End Get
End Property
From within your Window that inherits from the WindowBase class you can test to see if you are in design mode or in runtime mode.
C#
if(IsInDesignMode)
// Do Something
Visual Basic
If IsInDesignMode Then
' Do Something
End If
Another piece of code that might come in handy in your WPF windows is the ability to read a resource dictionary XAML file and load it into the Resources of the Window. Below is the code you would add to the WindowBase class to do this.
C#
using System.IO;
using System.Windows.Markup;
public void OpenResourceDictionary(string fileName)
{
ResourceDictionary dic = null;
if (File.Exists(fileName))
{
using (FileStream fs = new FileStream(fileName, FileMode.Open))
dic = (ResourceDictionary)XamlReader.Load(fs);
this.Resources.MergedDictionaries.Add(dic);
}
else
throw new FileNotFoundException(
"Can't open resource file: " + fileName +
" in the method OpenResourceDictionary().");
}
Visual Basic
Imports System.IO
Imports System.Windows.Markup
Public Sub OpenResourceDictionary(ByVal fileName As String)
Dim dic As ResourceDictionary = Nothing
If File.Exists(fileName) Then
Using fs As New FileStream(fileName, FileMode.Open)
dic = DirectCast(XamlReader.Load(fs), ResourceDictionary)
End Using
Me.Resources.MergedDictionaries.Add(dic)
Else
Throw New FileNotFoundException( _
"Can't open resource file: " & fileName & _
" in the method OpenResourceDictionary().")
End If
End Sub
When you wish to load a new resource dictionary file at runtime into your Window you may do so with some very simple code from within your Window.
C#
OpenResourceDictionary("D:\Samples\Green.xaml");
Visual Basic
OpenResourceDictionary("D:\Samples\Green.xaml")
Summary
So, that is all there is to creating your own base Window class from which all your Window objects can inherit. There is a lot of functionality that you will want to make available to your Window classes. Creating a base Window class is a great way to expose this functionality. It just takes a little bit of tweaking to your XAML and your code-behind to get all this great functionality.
NOTE: You can download the complete sample code at my website. http://www.pdsa.com/downloads. Choose Tips & Tricks, then "WPF Window Inheritance" from the drop-down.
Good Luck With Your Coding,
Paul Sheriff
** SPECIAL OFFER FOR MY BLOG READERS **
Visit http://www.pdsa.com/Event/Blog for a free eBook on "Fundamentals of N-Tier".
After my last blog post on “Create a Login Window in WPF”, I had a lot of requests for how to create the same login screen in Silverlight 3. There are actually just a few changes that had to be made to get the same look in feel in Silverlight 3. Figure 1 shows what this login screen looks like under Silverlight.

Figure 1: A Login Screen in Silverlight 3 (SLLogin.jpg)
Let’s take a look at how to create this screen in Silverlight.
Create a Silverlight Application
The first step is to create a Silverlight Application using VS.NET 2008. Once you have this created, open the MainPage.xaml that is created by the template. For this particular User Control you will set a specific width and height on the Grid control.
<Grid x:Name="LayoutRoot" Width="500" Height="200">
</Grid>
Next you will create some resources to help style the various elements you will be using on this Silverlight page. I have set some specific height properties on the controls for this page. I did this so the controls would not look stretched out. There might be a better way to do this, but I am still just learning Silverlight!
<Grid.Resources>
<Style x:Key="tbStyle"
TargetType="TextBlock">
<Setter Property="Margin"
Value="4"></Setter>
</Style>
<Style x:Key="textBoxStyle"
TargetType="TextBox">
<Setter Property="Margin"
Value="4"></Setter>
<Setter Property="MinWidth"
Value="200"></Setter>
<Setter Property="HorizontalAlignment"
Value="Left"></Setter>
</Style>
<Style x:Key="passStyle"
TargetType="PasswordBox">
<Setter Property="Margin"
Value="4"></Setter>
<Setter Property="MinWidth"
Value="200"></Setter>
<Setter Property="HorizontalAlignment"
Value="Left"></Setter>
</Style>
<Style x:Key="buttonStyle"
TargetType="Button">
<Setter Property="Margin"
Value="6"></Setter>
<Setter Property="Padding"
Value="4"></Setter>
<Setter Property="MinWidth"
Value="50"></Setter>
</Style>
</Grid.Resources>
The Border
Now that you have created the Grid size and the resources to be used within the Grid you now 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”. To achieve the shadow effect on this window, you will use the Border.Effect and the DropShadowEffect. Below is the xaml for the Border control.
<Border CornerRadius="10"
BorderBrush="Gray"
BorderThickness="3"
Background="Beige"
Padding="4">
<Border.Effect>
<DropShadowEffect Color="Gray"
Opacity=".50"
ShadowDepth="16" />
</Border.Effect>
...
...
</Border>
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. The first column is for the image of the key, the second is for the labels and the third is for the TextBox, PasswordBox and Button controls.
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="60" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
...
...
</Grid>
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 Grid.Column, Grid.Row and Grid.RowSpan attributes that are set on the StackPanel. The Grid.Row and Grid.Column specify in which row and column of the grid you wish to display the StackPanel. The Grid.RowSpan 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 Key.jpg file located in the Images folder. A drop shadow effect is applied to this image control just like you did with the Border control.
<StackPanel Grid.Column="0"
Grid.Row="0"
Grid.RowSpan="3">
<Image Name="imgKey"
Margin="8"
Source="Images/Key.jpg">
<Image.Effect>
<DropShadowEffect Color="Gray"
Opacity=".50"
ShadowDepth="8" />
</Image.Effect>
</Image>
</StackPanel>
The Large Title Label
The large label across the top of the login screen is simply a Label control with the appropriate Grid.Row, Grid.Column and Grid.ColumnSpan 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.
<Label Grid.Column="1"
Grid.Row="0"
Grid.ColumnSpan="2"
FontSize="18"
Margin="10"
Text="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 Silverlight development. Each control is placed into a specific row and column of the Grid control. Instead of a Label control like you use in WPF, a TextBlock control is used in Silverlight.
<TextBlock Style="{StaticResource tbStyle}"
Grid.Column="1"
Grid.Row="0"
Grid.ColumnSpan="2"
FontSize="18"
Margin="10"
Text="Please Login To Access This Application" />
<TextBlock Style="{StaticResource tbStyle}"
Grid.Column="1"
Grid.Row="1"
Text="User Name" />
<TextBox Style="{StaticResource textBoxStyle}"
Grid.Column="2"
Grid.Row="1"
Name="txtUserName" />
<TextBlock Style="{StaticResource tbStyle}"
Grid.Column="1"
Grid.Row="2">Password</TextBlock>
<PasswordBox Style="{StaticResource passStyle}"
Grid.Column="2"
Grid.Row="2"
Name="txtPassword" />
Notice the use of the Style attribute to apply the styles defined in the Grid.Resources section. In WPF you can apply global styles to a target control. In Silverlight you have to assign the style individually to each control.
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.
<StackPanel Grid.Column="1"
Grid.Row="3"
Margin="10"
HorizontalAlignment="Center"
Orientation="Horizontal">
<Button Style="{StaticResource buttonStyle}"
Name="btnCancel"
Content="Cancel">
<Button.Effect>
<DropShadowEffect Color="Gray"
Opacity=".50"
ShadowDepth="8" />
</Button.Effect>
</Button>
<Button Style="{StaticResource buttonStyle}"
Name="btnLogin"
Content="Login">
<Button.Effect>
<DropShadowEffect Color="Gray"
Opacity=".50"
ShadowDepth="8" />
</Button.Effect>
</Button>
</StackPanel>
Summary
That is all there is to creating a nice looking login screen in Silverlight 3. Using the DropShadowEffect can add some spice to an otherwise flat-looking screen. I did not show any code for the login process as that will be dependent on your particular application. However, I hope this article gave you some ideas on how to layout screens in Silverlight 3.
NOTE: You can download the complete sample code at my website. http://www.pdsa.com/downloads. Choose Tips & Tricks, then "Silverlight 3 Login Screen" from the drop-down.
Good Luck With Your Coding,
Paul Sheriff
** SPECIAL OFFER FOR MY BLOG READERS **
Visit http://www.pdsa.com/Event/Blog for a free eBook on "Fundamentals of N-Tier".
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.
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.
<Window ...
WindowStartupLocation="CenterScreen"
AllowsTransparency="True"
ShowInTaskBar=False
Background="Transparent"
WindowStyle="None"
SizeToContent="WidthAndHeight"
FocusManager.FocusedElement=
"{Binding ElementName=txtUserName}">
...
...
</Window>
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 FocusManager.FocusedElement 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 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 Border.Effect 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.
<Border CornerRadius="10"
BorderBrush="Gray"
BorderThickness="3"
Background="Beige"
Margin="24"
Padding="4">
<Border.Effect>
<DropShadowEffect Color="Gray"
Opacity=".50"
ShadowDepth="16" />
</Border.Effect>
...
...
</Border>
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.
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="60" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
...
...
</Grid>
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 Grid.Column, Grid.Row and Grid.RowSpan attributes that are set on the StackPanel. The Grid.Row and Grid.Column specify in which row and column of the grid you wish to display the StackPanel. The Grid.RowSpan 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 Key.jpg file located in the /Images folder. A drop shadow effect is applied to this image control just like you did with the Border control.
<StackPanel Grid.Column="0"
Grid.Row="0"
Grid.RowSpan="3">
<Image Name="imgKey"
Margin="8"
Source="/Images/Key.jpg">
<Image.Effect>
<DropShadowEffect Color="Gray"
Opacity=".50"
ShadowDepth="8" />
</Image.Effect>
</Image>
</StackPanel>
The Large Title Label
The large label across the top of the login screen is simply a Label control with the appropriate Grid.Row, Grid.Column and Grid.ColumnSpan 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.
<Label Grid.Column="1"
Grid.Row="0"
Grid.ColumnSpan="2"
FontSize="18"
Margin="10">Please Login To Access This Application
</Label>
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.
<Label Grid.Column="1"
Grid.Row="1">User Name</Label>
<TextBox Grid.Column="2"
Grid.Row="1"
ToolTip="Enter Your User Name"
Name="txtUserName" />
<Label Grid.Column="1"
Grid.Row="2">Password</Label>
<PasswordBox Grid.Column="2"
Grid.Row="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.
<StackPanel Grid.Column="2"
Grid.Row="3"
Margin="10"
HorizontalAlignment="Center"
Orientation="Horizontal">
<Button Name="btnCancel"
IsCancel="True"
Content="Cancel"
Click="btnCancel_Click">
<Button.Effect>
<DropShadowEffect Color="Gray"
Opacity=".50"
ShadowDepth="8" />
</Button.Effect>
</Button>
<Button Name="btnLogin"
IsDefault="True"
Content="Login"
Click="btnLogin_Click">
<Button.Effect>
<DropShadowEffect Color="Gray"
Opacity=".50"
ShadowDepth="8" />
</Button.Effect>
</Button>
</StackPanel>
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.
C#
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
this.Close();
}
Visual Basic
Private Sub btnCancel_Click(ByVal sender As System.Object, _
ByVal e As System.Windows.RoutedEventArgs)
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 System.Object, _
ByVal e As System.Windows.RoutedEventArgs)
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.
C#
private void DisplayLoginScreen()
{
frmLogin frm = new frmLogin();
frm.Owner = this;
frm.ShowDialog();
if (frm.DialogResult.HasValue && frm.DialogResult.Value)
MessageBox.Show("User Logged In");
else
this.Close();
}
Visual Basic
Private Sub DisplayLoginScreen()
Dim frm As New frmLogin()
frm.Owner = Me
frm.ShowDialog()
If frm.DialogResult.HasValue And frm.DialogResult.Value Then
MessageBox.Show("User Logged In")
Else
Me.Close()
End If
End Sub
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.
NOTE: You can download the complete sample code at my website. http://www.pdsa.com/downloads. Choose Tips & Tricks, then "WPF Login Screen" from the drop-down.
Good Luck With Your Coding,
Paul Sheriff
** SPECIAL OFFER FOR MY BLOG READERS **
Visit http://www.pdsa.com/Event/Blog for a free eBook on "Fundamentals of N-Tier".
Almost every application has a configuration file used to store global settings. What would be cool is to have a global settings class that reads this data from the .Config file, then can be used to bind to UI elements within your WPF application. This is actually very easy to accomplish using the data-binding features in WPF.
Creating a Config Class
Below is a sample App.Config file you might add to a WPF application with a couple of settings in the <appSettings> element in the file.
<configuration>
<appSettings>
<add key="DefaultState" value="CA"/>
<add key="IsActiveFlag" value="true"/>
</appSettings>
</configuration>
These two values might be used as defaults to feed UI elements in your WPF application. So, you now need to create a class that will read these values from the .Config file. Below is a class named MySettings that has two properties; DefaultState and IsActiveFlag. In each of the Get methods is a call to the ConfigurationManager.AppSettings property to retrieve the appropriate element from the .Config file.
C#
public class MySettings
{
public MySettings()
{
}
public string DefaultState
{
get {
return ConfigurationManager.AppSettings
["DefaultState"].ToString();
}
}
public bool IsActiveFlag
{
get {
return Convert.ToBoolean(ConfigurationManager.AppSettings
["IsActiveFlag"]);
}
}
public void Refresh()
{
ConfigurationManager.RefreshSection("appSettings");
}
}
Visual Basic
Public Class MySettings
Public ReadOnly Property DefaultState() As String
Get
Return
ConfigurationManager.AppSettings("DefaultState").ToString()
End Get
End Property
Public ReadOnly Property IsActiveFlag() As Boolean
Get
Return Convert.ToBoolean( _
ConfigurationManager.AppSettings("IsActiveFlag"))
End Get
End Property
Public Sub Refresh()
ConfigurationManager.RefreshSection("appSettings")
End Sub
End Class
Now, you need to create an instance of this class in your WPF application and bind each property to a UI element.
Create Instance of Config Settings Class
Open your App.xaml or Application.xaml file and add a new namespace at the top that references your Namespace or application name. In my sample, I created a WPF application called WPFBindConfigSettings, so that is the name that I need to reference as shown in the code below.
<Application x:Class="WPFBindConfigSettings.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:WPFBindConfigSettings"
StartupUri="frmBindSettings.xaml">
<Application.Resources>
<ObjectDataProvider x:Key="odpSettings"
ObjectType="{x:Type src:MySettings}" />
</Application.Resources>
</Application>
In the <Application.Resources> element you will add a <ObjectDataProvider> element that will create an instance of your MySettings class. As you can see in the above code that this is as simple as setting the ObjectType attribute in the ObjectDataProvider to src:MySettings. Set the Key attribute for this ObjectDataProvider object to “odpSettings” as you will need to reference this resource from any window you create in your WPF application.
Bind to WPF UI
Now, let’s use this ObjectDataProvider to bind the values from the MySettings class to UI elements on a WPF Window as shown in Figure 1.

Figure 1: You can bind settings from a Config
Below is the XAML to create the form shown in Figure 1.
<Grid>
<StackPanel>
<StackPanel Orientation="Horizontal">
<Label>Default State</Label>
<TextBox Name="txtDefaultState"
Width="50"
Text="{Binding Source={StaticResource odpSettings},
Path=DefaultState, Mode=OneWay}">
</TextBox>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Label>Is Active Flag?</Label>
<CheckBox Name="chkIsActiveFlag"
IsChecked="{Binding Source={StaticResource
odpSettings}, Path=IsActiveFlag,
Mode=OneWay}"
VerticalAlignment="Center">
</CheckBox>
</StackPanel>
<Button Name="btnRefresh"
Click="btnRefresh_Click">Refresh</Button>
</StackPanel>
</Grid>
In the above code you use the {Binding} syntax to read the values from the resource named “odpSettings” which is the Key value you created for the ObjectDataProvider in the App.xaml file. You must set the Mode=OneWay since the properties are read-only in the MySettings class. That is all there is to binding to the settings contained in the .Config file.
Refreshing the Config Settings
If you modify the values in the .Config file you will want to refresh the values in the ObjectDataProvider and ultimately in the UI. This can be easily accomplished with just a little bit of VB or C# code. Notice the Refresh method in the MySettings class presented above. The Refresh method in the MySettings class calls the ConfigurationManager.RefreshSection method to re-read a section in a .Config file. After refreshing the values from the .Config file you will want to have the UI be updated as well. You can accomplish this in a few different ways.
-
Refresh each individual control (this approach takes the most code)
-
Refresh the ObjectDataProvider which automatically refreshes the controls
-
Implement the INotifyPropertyChanged interface. This is the best method to use
Let’s now take a look at each of these three approaches.
Refresh Each Individual Control
The first method is to refresh each individual control after calling the Refresh method on the MySettings class. This involves getting a reference to the MySettings instance in the ObjectDataProvider class. You can retrieve an instance of the ObjectDataProvider by calling the FindResource method on an instance of the current application. This is done in the source code shown in the following listing. Once you have the reference to the ObjectDataProvider you can grab an instance of the MySettings class and call the Refresh method on that object. This will cause the class to refresh the settings from the changed .Config file.
C#
private void RefreshControls()
{
MySettings opts = (MySettings)((ObjectDataProvider)
Application.Current.
FindResource("odpSettings")).ObjectInstance;
opts.Refresh();
txtDefaultState.GetBindingExpression(
TextBox.TextProperty).UpdateTarget();
chkIsActiveFlag.GetBindingExpression(
CheckBox.IsCheckedProperty).UpdateTarget();
}
Visual Basic
Private Sub RefreshControls()
Dim opts As MySettings = DirectCast(DirectCast( _
Application.Current.FindResource("odpSettings"), _
ObjectDataProvider).ObjectInstance, MySettings)
opts.Refresh()
txtDefaultState.GetBindingExpression( _
TextBox.TextProperty).UpdateTarget()
chkIsActiveFlag.GetBindingExpression( _
CheckBox.IsCheckedProperty).UpdateTarget()
End Sub
Next, you can update the target of the bindings of each control by using the GetBindingExpression method on the specific property on the control and then calling the UpdateTarget method on that property. This will force the control to refresh its binding.
Refresh the Data Provider
The second method you can use to refresh the data on the UI is to tell the ObjectDataProvider object to call its Refresh method. Again you need to get the instance of the ObjectDataProvider from the Application.Current property and call its FindResource method. You then get a reference to the MySettings object and call its Refresh method. Next, call the Refresh method on the ObjectDataProvider instance. This automatically refreshes all UI elements that are bound to this ObjectDataProvider.
C#
private void RefreshDataProvider()
{
ObjectDataProvider dp =
(ObjectDataProvider)Application.Current.
FindResource("odpSettings");
MySettings opts = (MySettings)dp.ObjectInstance;
opts.Refresh();
dp.Refresh();
}
Visual Basic
Private Sub RefreshDataProvider()
Dim dp As ObjectDataProvider = _
DirectCast(Application.Current.FindResource("odpSettings"), _
ObjectDataProvider)
Dim opts As MySettings = DirectCast(dp.ObjectInstance, _
MySettings)
opts.Refresh()
dp.Refresh()
End Sub
Implement INotifyPropertyChanged
The third method you can use to refresh the data on the UI is to implement the INotifyPropertyChanged event on the MySettings class. When you implement this interface, you write code that will inform any data bindings that the property, or properties, on a class have changed.
You will modify the MySettings class in order to implement this interface. First off, you will need to import the System.ComponentModel namespace.
C#
using System.ComponentModel;
Visual Basic
Imports System.ComponentModel
Next, change the class definition to implement the interface.
C#
public class MySettings : INotifyPropertyChanged
Visual Basic
Public Class MySettings
Implements INotifyPropertyChanged
Next you declare your intention to use the PropertyChangedEventHandler event procedure. To make it easier to call this from within the class, it is a good idea to create a method to raise this event. Below is code that needs to be added to the MySettings class.
C#
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null) {
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
Visual Basic
Public Event PropertyChanged(ByVal sender As Object, _
ByVal e As System.ComponentModel.PropertyChangedEventArgs) _
Implements System.ComponentModel. _
INotifyPropertyChanged.PropertyChanged
Protected Sub RaisePropertyChanged(ByVal propertyName As String)
RaiseEvent PropertyChanged(Me, _
New PropertyChangedEventArgs(propertyName))
End Sub
The code above takes care of notifying all bound objects about any changes to any properties in this class. Of course, it is up to you from within the class to call the RaisePropertyChanged method anytime you change the values from within the class. This means you need to change the Refresh method in the MySettings class to call the RaisePropertyChanged method.
C#
public void Refresh()
{
ConfigurationManager.RefreshSection("appSettings");
RaisePropertyChanged("DefaultState");
RaisePropertyChanged("IsActiveFlag");
}
Visual Basic
Public Sub Refresh()
ConfigurationManager.RefreshSection("appSettings")
RaisePropertyChanged("DefaultState")
RaisePropertyChanged("IsActiveFlag")
End Sub
The lines in bold are used to raise the PropertyChanged event so all bound objects to these properties are notified. Now you can call the following method in the Refresh button’s click event procedure in the WPF window.
C#
private void RefreshINotify()
{
MySettings opts = (MySettings)((ObjectDataProvider)
Application.Current.FindResource("odpSettings")).ObjectInstance;
opts.Refresh();
}
Visual Basic
Private Sub RefreshINotify()
Dim opts As MySettings = _
DirectCast(DirectCast( _
Application.Current.FindResource("odpSettings"), _
ObjectDataProvider).ObjectInstance, MySettings)
opts.Refresh()
End Sub
If you now run this sample and modify the .Config file and click the Refresh button, you will see the change made.
Summary
The data binding features of WPF are useful for more than just binding to database data. In this article you discovered how you can use the binding features to bind .Config file data to UI elements and how to refresh that data when the .Config file changes. You should use the INotifyPropertyChanged interface in most of the classes you create as this will make data binding to UI notifications almost automatic.
Download the Complete Sample
We have the completed sample for this article available on our website at http://www.pdsa.com/Downloads. Once there, select “Tips and Tricks” from the Category drop-down. Then select “WPF Sample – Bind Config Settings” from the Item drop-down.
Good Luck With Your Coding,
Paul Sheriff
** SPECIAL OFFER FOR MY BLOG READERS **
Visit http://www.pdsa.com/Event/Blog for a free eBook on "Fundamentals of N-Tier".
When creating a splash screen or to just have a different look for the windows in your WPF application, you might wish to eliminate the border to give it a custom look (see Figure 1). This can be done very easily with WPF.
Figure 1: A WPF window that has no border.
Setting Window Attributes
To get a border-less window, you need to set the following attributes on your Window.
- WindowStyle="None"
- ShowInTaskbar="False"
- AllowsTransparency="True"
- Background="Transparent"
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 doing a splash screen you probably won’t want this window to show up in the Task Bar as it is only going to be there for a very short time. 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.
The complete XAML code for the Window shown in Figure 1 looks like the following:
<Window x:Class="WPFExtras.frmWindowNoBorder"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
WindowStyle="None"
ResizeMode="NoResize"
ShowInTaskbar="False"
AllowsTransparency="True"
Background="Transparent"
WindowStartupLocation="CenterScreen"
Height="300"
Width="300">
<!-- Creates the shadow on the right and bottom -->
<Border BorderBrush="Gray"
BorderThickness="0,0,2,2"
CornerRadius="10"
Background="Beige">
<!-- Create space between shadow and the next border -->
<Border BorderBrush="Transparent"
BorderThickness="5"
CornerRadius="10">
<!-- The inner border -->
<Border BorderBrush="Black"
BorderThickness="1.5"
CornerRadius="10">
<StackPanel VerticalAlignment="Bottom" Margin="10">
<Button Style="{StaticResource BasicControl}"
Click="Button_Click">Close Me</Button>
</StackPanel>
</Border>
</Border>
</Border>
</Window>
The XAML code for this Window uses 3 <Border> elements to create the shadow effect. The outer border is the shadow border that displays just on the right and the bottom. This is accomplished by setting the BorderThickness attribute to 0,0,2,2. The next border is to just give some space between the outer “shadow” border and the inner border. Notice the use of the CornerRadius attribute to give a nice rounded border effect.
Summary
Creating a border-less window is a very straight-forward process in WPF. Just by setting a few attributes will remove the border. Then you can create your own border by using the <Border> element. Or you could use any type of container you want to contain the controls on your Window.
Good Luck With Your Coding,
Paul Sheriff
** SPECIAL OFFER FOR MY BLOG READERS **
Visit http://www.pdsa.com/Event/Blog for a free eBook on "Fundamentals of N-Tier".
In WPF if you want to layout a typical business form like the one shown in Figure 1, most people would use a Grid control with rows and columns. However, you may also use a StackPanel control. While sometimes you might need the re-sizing capabilities of a Grid, you sometimes just need a fixed size. For a fixed-size form a StackPanel control can be a little easier and offers a little more flexibility.
Figure 1: A business form using a StackPanel
Using a Grid
If you were to layout the above form using a Grid control you might write code that looks like the following:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Label Grid.Column="0" Grid.Row="0">FirstName</Label>
<TextBox Grid.Column="1" Grid.Row="0" Name="txtFirst" />
<Label Grid.Column="0" Grid.Row="1">Last Name</Label>
<TextBox Grid.Column="1" Grid.Row="1" Name="txtLast" />
<Button Grid.Column="1" Grid.Row="2" Name="btnClose">
Close
</Button>
</Grid>
In the above XAML code you need to assign the Grid.Row and a Grid.Column properties on each Label, TextBox and Button control. This is how the XAML knows where to place each control in the Grid.
Using a StackPanel Control
Now, let’s layout the same form using a series of StackPanel controls. Each StackPanel for each “row” will have the Orientation set to “Horizontal”. There will also be a Style setup for each Label to set the Width property to a specific amount so each text box will be aligned correctly. Below is what the form that uses the StackPanel looks like.
<StackPanel>
<StackPanel Orientation="Horizontal">
<Label>First Name</Label>
<TextBox Name="txtFirst"></TextBox>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Label>Last Name</Label>
<TextBox Name="txtLast"></TextBox>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Label></Label>
<Button Name="btnClose">Close</Button>
</StackPanel>
</StackPanel>
Now here are the styles that you add to the Window.Resources on this window to give the form its structure.
<Window.Resources>
<Style TargetType="Label">
<Setter Property="Width" Value="100" />
</Style>
<Style TargetType="TextBox">
<Setter Property="MinWidth" Value="160" />
</Style>
</Window.Resources>
Now, there are advantages and disadvantages to using a Grid and to using a StackPanel. A Grid is great because the text box controls will automatically re-size as the user sizes the form. However, if you have several rows and you wish to insert a row in the middle, you need to renumber each row after the new row. Sometimes the VS.NET designer will renumber them for you, but sometimes it won’t. Or, if you wish to move an existing row below or above another, you will also be doing a lot of manual renumbering.
Many business forms do not require re-sizing, so in this case a StackPanel works very well. Using styles gives you the same flexibility as the Grid column definitions, so this is very nice. Also, the ability to just move rows around without worrying about renumbering is a great benefit. However, you do lose the re-sizing capabilities, so this is a tradeoff.
Summary
As with most WPF applications, there are typically more ways than one to accomplish the same thing. This is probably the most frustrating part of learning WPF. Here I showed you a couple different ways to layout the same business form. Each method has its advantages and disadvantages, so it will be up to you to determine when to use each method.
Not too long ago we received a text file of customer names. The problem with the file is it just had one field "Name". One of the requirements of our database application was to have a first name field and a last name field so our customer could search for their customers on either field. As a result we needed to take this text file and split out the data into the two fields from the one.
As we looked into this file, we noticed that the data was in complete disarray! Some of the names were entered like "First Last", and some in the format "Last, First". So, we needed to perform a little string parsing to get the data into our database table. The following is a simplified version of the routine we wrote to attempt to handle each format and create a new Customer object that we could then use to populate our database table.
First we needed to create a Customer class. We created an instance of this Customer class and passed in the "name" value read from the text file into the method of the Customer class named NameSplit().
C#
class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public void NameSplit(string name)
{
if(name.Length > 0)
{
// Check for a comma
if(name.IndexOf(",") > 0)
{
LastName = name.Substring(0, name.IndexOf(",")).Trim();
FirstName = name.Substring(name.IndexOf(",") + 1).Trim();
}
else if(name.IndexOf(" ") > 0)
{
FirstName = name.Substring(0, name.IndexOf(" ")).Trim();
LastName = name.Substring(name.IndexOf(" ") + 1).Trim();
}
}
}
}
Visual Basic
Public Class Customer
Private mFirstName As String
Private mLastName As String
Public Property FirstName() As String
Get
Return mFirstName
End Get
Set(ByVal Value As String)
mFirstName = Value
End Set
End Property
Public Property LastName() As String
Get
Return mLastName
End Get
Set(ByVal Value As String)
mLastName = Value
End Set
End Property
Public Sub NameSplit(ByVal name As String)
If name.Length > 0 Then
' First check for a comma to see if they entered Last, First
If name.IndexOf(",") > 0 Then
mLastName = name.Substring(0, name.IndexOf(",")).Trim()
mFirstName = name.Substring(name.IndexOf(",") + 1).Trim()
ElseIf name.IndexOf(" ") > 0 Then
mFirstName = name.Substring(0, name.LastIndexOf(" ")).Trim()
mLastName = name.Substring(name.LastIndexOf(" ") + 1).Trim()
End If
End If
End Sub
End Class
To test out this method, use the following code:
C#
private void TestCustomerSplit()
{
Customer cust;
cust = new Customer();
cust.NameSplit("Bruce Jones");
MessageBox.Show(cust.FirstName + " " + cust.LastName);
cust = new Customer();
cust.NameSplit("Jones, Bruce");
MessageBox.Show(cust.FirstName + " " + cust.LastName);
}
Visual Basic
Private Sub TestCustomerSplit()
Dim cust As Customer
cust = New Customer()
cust.NameSplit("Bruce Jones")
MessageBox.Show(cust.FirstName & " " & cust.LastName)
cust = New Customer()
cust.NameSplit("Jones, Bruce")
MessageBox.Show(cust.FirstName & " " & cust.LastName)
End Sub
Another way to accomplish this task would have been to use the Split() method of the String class. You can split a string on a specific character like a space or a comma. You then end up with an array of each name. I will leave that as an exercise for you to do! :)
You just have to love the string parsing capabilities of .NET! Just a little bit of code was all it took to make this job of turning different formats into something that was much easier to work with.
Good Luck With Your Coding,
Paul Sheriff
** SPECIAL OFFER FOR MY BLOG READERS **
Visit http://www.pdsa.com/Event/Blog for a free eBook on "Fundamentals of N-Tier".
More Posts
Next page »