Introduction To WPF
Introduction To WPF
_____________________________________________________________________________________
_________________
1. WPF
WPF stands for Windows Presentation Foundation. It's a re-invention of a UI for Desktop
applications using WPF. Apart from dropping controls on "Windows Forms" just as developers
have been doing for years, WPF provides an extra rapid boost to the application
development including Rich User Interface, Animation and much more.
Windows Presentation Foundation (WPF) is the code-name of the presentation (userinterfaces) sub system in Windows programming model and is used to create user
interfaces. If you have been programming .NET, you must be familiar with Windows Forms
and ASP.NET. Windows Forms are used to build Windows client application and ASP.NET is
used to build Web applications.
Well, WPF is a new technology that may be used instead of both Windows Forms and
ASP.NET.
WPF also allows programmers to develop web pages which can be run within a web browser.
In a nutshell the following things can be done using WPF:
Can provide smooth graphical effects such as drop shadows and color gradients.
Can use shared styles which can be used across the same controls to provide the
same theme, skin and design.
Can easily draw vector graphics that scale without jagged aliasing.
2. XAML
XAML stands for "eXtensible Application Markup Language". Applications load XAML
code to load the UI. XAML has its own objects to represent windows, controls,
resources, styles and other objects.
XAML is also considered to be a Declarative language.
3.What
is Declarative Language?
<StackPanel>
<Image Margin="5" Height="50" Source="Frog.jpg"/>
<Label Margin="5" Content="Frog"/>
</StackPanel>
Image and label are being placed under a StackPanel Control.
4. Silverlight
5. Content Controls: Content Controls are primarily intended to hold content that the
user should see. They display something that the user should view but generally won't
modify. A few controls are in this category:
Border
BulletDecorator
Document Viewer
GroupBox
6. Layout Controls: They are primarily intended to contain and arrange other controls.
They position the controls they contain in various ways to make easier to design various
kinds of user interfaces. The following are the controls:
Canvas
DockPanel
Content Controls
Content Controls are mainly parent containers to hold the content. It displays information to the
user to be viewed but that generally won't be modified.
Before we start with content controls, the following aspects need to be clear:
1. Property: A Property specifies the object's appearance or behavior. For example, the
IsEnabled property specifies whether the user can interact with a control or not.
2.
Method: A Method is a routine that a control executes to perform something. For example
Coa unt Method counts the number of items available for the object or control.
3.
Event: An event is related when a control raises one to let your application know that
something has happened. For example TextBox raises a TextChanged event whenever its text
changes.
Content Controls
Border: It draws a broder around a single child control. It is used with the following
properties:
BulletDecorator: Displays an item and bullet in a bulleted list. This control's most
important property is Bullet, which should contain the object to be used as the item's
bullet.
Code snippet
<BulletDecorator>
<BulletDecorator.Bullet>
<ImageWidth="20"Height="20"Source="Leaf.bmp"Stretch="None"
HorizontalAlignment="Left"VerticalAlignment="Center" >
<Image.BitmapEffect>
<DropShadowBitmapEffect/>
</Image.BitmapEffect>
</Image>
</BulletDecorator.Bullet>
<LabelContent="Cricket"Foreground="Blue"/>
</BulletDecorator>
The above code snippet creates the first item in the Bulleted list. The bullet image can be
set in the <Image> source property as shown in the code.
ToolTip: Displays a tooltip for another object. For example, when a user hovers the
mouse on a textbox then a tooltip can be displayed for user input.
Code Snippet
<TextBoxMargin="70,10,10,0"VerticalAlignment="Top"Text="Name"ToolTip="The
customer's first name"Name="txtFirstName"Height="20" />
The above code snippet shows the use of tooltip, as it shows "The customers first name".
o None: The picture is not stretched at all and gets display at its original size.
o Fill: Stretches the image to fill the control and leads to picture distortion.
o Uniform: The picture is stretched at an equal amount vertically and horizontally to
make it fit in the Image control.
o UniformtoFill: The picture is stretched by the same amount vertically and
horizontally until it completely fills the Image control. If the picture doesn't have
the same width-to-height ratio as the Image control, then some portion of the
image will overflow out of the edges of the control and will be clipped.
o StretchDirection: It determines whether the picture can be enlarged or shrunk to satisfy
the stretch property. It takes two parameters as values:
MediaElement: Plays an audio or video file. By default it starts playing the media
file. To let the program control the media set the control's LoadBehavior property to
Manual.
Code Snippet
The Following XAML code defines two Media Element controls, one plays video and the
other plays audio file.
<MediaElementx:Name="meVideo"Source="myIndia.wmv"LoadedBehavior="Manual
"
Margin="100,24,0,0"HorizontalAlignment="Left"VerticalAlignment="Top"Height="80"
/>
<MediaElementx:Name="meAudio"Source="LightChimes.wav" LoadedBehavior="Ma
nual"
Margin="0,120,110,30"HorizontalAlignment="Right" Width="120" />
ListView
The Width and Height properties represent the width and the height of a ListView. The
Name property represents the name of the control, which is a unique identifier of a
control. The Margin property tells the location of a ListView on the parent control. The
HorizontalAlignment and VerticalAlignment properties are used to set horizontal and
vertical alignments.
The following code snippet sets the name, height, and width of a ListView control. The
code also sets horizontal alignment to left and vertical alignment to top.
<ListView Margin="10,10,0,13" Name="ListView1" HorizontalAlignment="Left
"
VerticalAlignment="Top" Width="194" Height="200" />
Figure 2.
On button click event handler, we add the content of TextBox to the ListView by calling
ListView.Items.Add method. The following code adds TextBox contents to the ListView
items.
private void button1_Click(object sender, RoutedEventArgs e)
{
ListView1.Items.Add(textBox1.Text);
}
On button click event handler, we add the content of TextBox to the ListView by calling
ListView.Items.Add method.
Now if you enter text in the TextBox and click Add Item button, it will add contents of
the TextBox to the ListView.
The button click event handler looks like following. On this button click, we find the
index of the selected item and call ListView.Items.RemoveAt method as following.
private void DeleteButton_Click(object sender, RoutedEventArgs e)
{
ListView1.Items.RemoveAt
(ListView1.Items.IndexOf(ListView1.SelectedItem));
}
The FontFamily, FontSize, and FontWeight are used to set a font of a ListViewItem. The
following code snippet sets font verdana, size 12, and bold of a ListViewItem.
<ListViewItem Background="LightCoral" Foreground="Red" Content="Coffie"
FontFamily="Verdana" FontSize="12" FontWeight="
Bold"></ListViewItem>
After changing my code for all 5 ListViewItems, the ListView looks like Figure 5.
I change the code of ListViewItems and add following CheckBoxes to the items. As you
may see, I have set the name of the CheckBoxes using Name property. If you need to
access these CheckBoxes, you may access them in the code using their Name property.
<ListViewItem Background="LightCoral" Foreground="Red"
FontFamily="Verdana" FontSize="12" FontWeight="Bold">
<CheckBox Name="CoffieCheckBox">
<StackPanel Orientation="Horizontal">
<Image Source="coffie.jpg" Height="30"></Image>
<TextBlock Text="Coffie"></TextBlock>
</StackPanel>
</CheckBox>
</ListViewItem>
<ListViewItem Background="LightGray" Foreground="Black"
FontFamily="Georgia" FontSize="14" FontWeight="Bold">
<CheckBox Name="TeaCheckBox">
<StackPanel Orientation="Horizontal">
<Image Source="tea.jpg" Height="30"></Image>
<TextBlock Text="Tea"></TextBlock>
</StackPanel>
</CheckBox>
</ListViewItem>
<ListViewItem Background="LightBlue" Foreground="Purple"
FontFamily="Verdana" FontSize="12" FontWeight="Bold">
<CheckBox Name="OrangeJuiceCheckBox">
<StackPanel Orientation="Horizontal">
<Image Source="OrangeJuice.jpg" Height="40"></Image>
<TextBlock Text="OrangeJuice"></TextBlock>
</StackPanel>
</CheckBox>
</ListViewItem>
<ListViewItem Background="LightGreen" Foreground="Green"
FontFamily="Georgia" FontSize="14" FontWeight="Bold">
<CheckBox Name="MilkCheckBox">
<StackPanel Orientation="Horizontal">
<Image Source="Milk.jpg" Height="30"></Image>
<TextBlock Text="Milk"></TextBlock>
</StackPanel>
</CheckBox>
</ListViewItem>
<ListViewItem Background="LightBlue" Foreground="Blue"
FontFamily="Verdana" FontSize="12" FontWeight="Bold">
<CheckBox Name="IcedTeaCheckBox">
<StackPanel Orientation="Horizontal">
<Image Source="IcedTea.jpg" Height="30"></Image>
<TextBlock Text="Iced Tea"></TextBlock>
</StackPanel>
</CheckBox>
</ListViewItem>
<ListViewItem Background="LightSlateGray" Foreground="Orange"
/// <summary>
/// Generate data. This method can bring data from a database or XML
file
/// </summary>
/// <returns></returns>
private ArrayList LoadListViewData()
On the Window loaded event, we create and load data items to the ListView by setting
the ItemsSource property to an ArrayList.
{
// Get data from somewhere and fill in my local ArrayList
myDataList = LoadListViewData();
// Bind ArrayList with the ListView
LeftListView.ItemsSource = myDataList;
}
TextBox Control
<TextBox x:Name="TextBox1" Height="30" Width="200"
Text="Hello! This is TextBox Eample."
Margin="10,10,0,0" VerticalAlignment="Top"
HorizontalAlignment="Left">
<TextBox.BorderBrush>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,1" >
<GradientStop Color="Green" Offset="0" />
<GradientStop Color="Yellow" Offset="1.0" />
</LinearGradientBrush>
</TextBox.BorderBrush>
</TextBox>
Figure 3
Setting Image as Background of a TextBox
To set an image as background of a TextBox, we can set an image as the Background of the
TextBox. The code snippet in Listing 4 sets the background of a TextBox to an image.
<TextBox.Background>
<ImageBrush ImageSource="Raj 022.JPG" />
</TextBox.Background>
Listing 4
AccessText Control
Creating an AccessText
The AccessText element represents an AccessText control in XAML.
<AccessText>_Click Me</AccessText>
The following code snippet adds an AccessText to a Button control. The button control click
event will be raised when you select the ALT+C keys on the keyboard.
<Button Name="Button1" Width="120" Height="50" Margin="33,70,59,124"
FontSize="16" Click="Button1_Click">
<AccessText>_Click Me</AccessText>
</Button>
Resources
provide a simple way to reuse commonly defined objects and values. If we are defining the
resource then we can use that resource a number of times. (Just like applying themes and css to
web pages).
StaticResource: StaticResources are resolved at compile time. Use StaticResources when it's
clear that you don't need your resource re-evaluated when fetching it static resources perform
better than dynamic resources.
In my WPF application page I have one textbox and two ellipses. In Window.Resources I defined
the SolidColorBrush and the Style properties.
<Window.Resources>
<SolidColorBrush x:Key="brush" Color="Green"></SolidColorBrush>
<SolidColorBrush x:Key="forbuttoncolor" Color="CadetBlue"></SolidColorBrush>
<Style TargetType="Border" x:Key="background">
<Setter Property="Background" Value="Orange"></Setter>
</Style>
<Style TargetType="TextBox" x:Key="TitleText">
<Setter Property="Background" Value="White"/>
<Setter Property="DockPanel.Dock" Value="Top"/>
<Setter Property="FontSize" Value="14"/>
<Setter Property="Foreground" Value="#4E87D4"/>
<Setter Property="FontFamily" Value="Tahoma"/>
<Setter Property="Margin" Value="50,50,50,0"/>
<Setter Property="Width" Value="300"></Setter>
</Style>
</Window.Resources>
In above code you can observe x: Key attribute. x: Key uniquely identifies elements that are
created and referenced in a XAML-defined dictionary.
As you can see, we have also defined an XPath attribute within the XMLDataProvider tag. This
path definition allows us to access the XML data based on the parent node "Favorites". Once
this has been defined, we need to prepare our bookmark data for display by binding it to a data
template. We can do this using the DataTemplate and Binding tags, also within the resources
portion of our XAML document.
<!-- create a data template to display the desired XML node values -->
<DataTemplate x:Key="BookmarkDataTemplate">
<StackPanel Margin="5">
<TextBlock FontSize="12" FontWeight="Bold" Foreground="White">
<TextBlock.Text>
<Binding XPath="Title"/>
</TextBlock.Text>
</TextBlock>
<TextBlock FontSize="10" Foreground="LightGray">
<TextBlock.Text>
<Binding XPath="URL"/>
</TextBlock.Text>
</TextBlock>
</StackPanel>
</DataTemplate>
A data template is now configured to accept both Title and URL node values, displaying each in
its own TextBlock. For purposes of layout, we have arranged these in a single StackPanel. The
Binding tag and XPath attribute have been used to define the specific XML nodes we are
interested in pulling data from.
All that is left is to use the data template to actually write our data to the screen. We do this by
referencing the data template in the main portion of our XAML document. Here we will bind the
data to a standard ListBox control using the ItemsSource and ItemTemplate properties.
<!-- write the data to the screen by binding the data template to a list box -->
<StackPanel>
<TextBlock FontSize="14" FontWeight="Bold" Margin="10">My Favorites</TextBlock>
<ListBox
Background="#999"
BorderThickness="2"
BorderBrush="White"
Margin="10"
ItemsSource="{Binding Source={StaticResource BookmarkData},
XPath=Bookmark}"
ItemTemplate="{StaticResource BookmarkDataTemplate}"/>
</StackPanel>
The ItemsSource property specifies a binding source referencing the original XML data we
defined in the resources portion of our document. The XPath property is set to "Bookmark", the
repeating child node within "Favorites". Lastly, the value for ItemTemplate is set to refer to the
key of our data template, "BookmarkDataTemplate".
Displayed in its entirity, our XAML file now looks like the following:
<Window x:Class="WindowsApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://sche
mas.microsoft.com/winfx/2006/xaml"
Title="WindowsApplication1" Width="550" Height="400" Name="Form1">
<Window.Resources>
<XmlDataProvider x:Key="BookmarkData" XPath="/Favorites">
<x:XData>
<Favorites xmlns="">
<Bookmark>
<Title>Google</Title>
<URL>http://www.google.com</URL>
</Bookmark>
<Bookmark>
<Title>Amazon</Title>
<URL>http://www.amazon.com</URL>
</Bookmark>
<Bookmark>
<Title>Slashdot</Title>
<URL>http://www.slashdot.com</URL>
</Bookmark>
<Bookmark>
<Title>Ars Technica</Title>
<URL>http://www.arstechnica.com</URL>
</Bookmark>
<Bookmark>
<Title>New Egg</Title>
<URL>http://www.newegg.com</URL>
</Bookmark>
</Favorites>
</x:XData>
</XmlDataProvider>
<!-- create a data template to display the desired XML node values -->
<DataTemplate x:Key="BookmarkDataTemplate">
<StackPanel Margin="5">
<TextBlock FontSize="12" FontWeight="Bold" Foreground="White
">
<TextBlock.Text>
<Binding XPath="Title"/>
</TextBlock.Text>
</TextBlock>
<TextBlock FontSize="10" Foreground="LightGray">
<TextBlock.Text>
<Binding XPath="URL"/>
</TextBlock.Text>
</TextBlock>
</StackPanel>
</DataTemplate>
</Window.Resources>
<!-- write the data to the screen by binding the data template to a list box -->
<StackPanel>
<TextBlock FontSize="14" FontWeight="Bold" Margin="10">My
Favorites</TextBlock>
<ListBox
Background="#999"
BorderThickness="2"
BorderBrush="White"
Margin="10"
ItemsSource="{Binding Source={StaticResource BookmarkData},
XPath=Bookmark}"
ItemTemplate="{StaticResource BookmarkDataTemplate}"/>
</StackPanel>
</Window>
When compiled, a window is displayed with a standard ListBox populated with our XML data: