0% found this document useful (0 votes)
182 views25 pages

Introduction To WPF

WPF (Windows Presentation Foundation) is a framework for building desktop applications and rich user interfaces in .NET. It allows creating animations, 3D graphics, and vector graphics that scale seamlessly. XAML is used to define the UI in WPF applications using a declarative syntax rather than imperative code. Content controls in WPF like Border, Image, Label, and ListView are used to display information to users that generally cannot be modified.

Uploaded by

Anubhav Girdhar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
182 views25 pages

Introduction To WPF

WPF (Windows Presentation Foundation) is a framework for building desktop applications and rich user interfaces in .NET. It allows creating animations, 3D graphics, and vector graphics that scale seamlessly. XAML is used to define the UI in WPF applications using a declarative syntax rather than imperative code. Content controls in WPF like Border, Image, Label, and ListView are used to display information to users that generally cannot be modified.

Uploaded by

Anubhav Girdhar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

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:

Draw normal controls and graphics.

Can easily load/play audio and video files.

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.

Transforming objects including shapes, controls and video.

Can create and animate 3D graphics.

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?

Declarative programming is a paradigm that express a logic of computation without


describing its control flow. So XAML is a declarative language since it describes what should
appear on a webpage and does not specify the possible interactions with it.
e.g.

<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

Silverlight (formerly known as WPF/e, where the e stands for "everywhere") is a


comprehensive version of WPF to build browser/web applications with a rich UI.

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

Image, Label, ListView, MediaElement, Popup, Progressbar etc.

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

Expander, Grid, StackPanel, StatusBar, TabControl etc.

WPF Content Controls

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:

o Background: The controls background Brush.


o BorderThickness: Determines the thickness of the Border's edges.
Code Snippet
<BorderHorizontalAlignment="Center"VerticalAlignment="Center"Width="150"Heigh
t="100"
CornerRadius="20"BorderBrush="#FFFF8000"BorderThickness="5">

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".

GroupBox: Displays a header and border around the control.


Code Snippet: The following code snippet creates a separate block to create an eyecatching UI for entering user information.
<GroupBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Header="Cu
stomer Information"Margin="8" BorderBrush="#FFD5DFE5">
<Grid Margin="5">
<Label Content="CustomerName" Height="28" HorizontalAlignment="Left" Margin=
"10,10,0,0" Name="label1"VerticalAlignment="Top" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="101,10,0,0" Name="text
Box1" VerticalAlignment="Top" Width="120" />
<Label Content="Address" Height="28" HorizontalAlignment="Left" Margin="10,44,
0,0" Name="label2"VerticalAlignment="Top" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="101,44,0,0" Name="text
Box2" VerticalAlignment="Top"Width="120" />
</Grid>
</GroupBox>
ScreenShot

Image: Displays a graphical Image.


o Stretch and it takes the following parameters as values:

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:

o UpOnly: Image can only be stretched to make it larger.


o DownOnly: Image can only be shrunk to make it smaller.

o Both: Image can be stretched or shrunk.


Code Snippet
<ImageWidth="Auto"Height="Auto"HorizontalAlignment="Stretch"VerticalAlignment
="Stretch"
Source="World.jpg"Stretch="UniformToFill"/>

Label: Displays text that the user can't modify.


<LabelContent="This is Comic Sans Serif, 20 point, bold, italic" FontFamily="Comic
Sans MS"FontSize="20"FontWeight="Bold"HorizontalAlignment="Center"/>

Content is the text being displayed on the Label control.


FontFamily is the style applied to the text displayed on the control.
FontSize determines the crispness of the text.
FontWeight makes the text appearance like Bold, Italic etc.

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" />

The Following methods are associated with the MediaElement Control.


meVideo.Play(); //meVideo is the control id and plays the video file.
meVideo.Pause(); //Pause the video.

meVideo.Position = new TimeSpan(0); //Rewind the video file by number of seconds


specified in TimeSpan() function.

ListView

The ListView tag represents a WPF ListView control in XAML.


<ListView></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" />

Adding ListView Items


A ListView control hosts a collection of ListViewItem. The following code snippet adds
items to a ListView control.
<ListView Margin="10,10,0,13" Name="ListView1" HorizontalAlignment="Left
"
VerticalAlignment="Top" Width="194" Height="200">
<ListViewItem Content="Coffie"></ListViewItem>
<ListViewItem Content="Tea"></ListViewItem>
<ListViewItem Content="Orange Juice"></ListViewItem>
<ListViewItem Content="Milk"></ListViewItem>
<ListViewItem Content="Iced Tea"></ListViewItem>
<ListViewItem Content="Mango Shake"></ListViewItem>
</ListView>

The above code generates Figure 1.

Figure 1. ListView with items


Adding ListView Items Dynamically
In the previous section, we saw how to add items to a ListView at design-time from
XAML. We can add items to a ListView from the code.
Now we change our UI and add a TextBox and a button control to the page. The XAML
code for the TextBox and Button controls look like following:
<TextBox Height="23" HorizontalAlignment="Left" Margin="8,14,0,0"
Name="textBox1" VerticalAlignment="Top" Width="127" />
<Button Height="23" Margin="140,14,0,0" Name="button1" VerticalAlignment
="Top"
HorizontalAlignment="Left" Width="76" Click="button1_Cli
ck">
Add Item
</Button>

The final UI looks like Figure 2.

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.

Figure 3. Adding ListView items dynamically


Deleting ListView Items
We can use ListView.Items.Remove or ListView.Items.RemoveAt method to delete an
item from the collection of items in the ListView. The RemoveAt method takes the index
of the item in the collection.
Now, we modify our application and add a new button called Delete Item. The XAML
code for this button looks like below.
<Button Height="23" Margin="226,14,124,0" Name="DeleteButton"
VerticalAlignment="Top" Click="DeleteButton_Click">
Delete Item</Button>

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));
}

Formatting and Styling


Formatting ListView Items
The Foreground and Background attributes of ListViewItem represents the background
and foreground colors of the item. The following code snippet sets background and
foreground color of a ListViewItem.

<ListViewItem Background="LightCoral" Foreground="Red" Content="Coffie">


</ListViewItem>

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>

I set the following properties of ListViewItems.


<ListViewItem Background="LightCoral" Foreground="Red" Content="Coffie"
FontFamily="Verdana" FontSize="12" FontWeight="
Bold"></ListViewItem>
<ListViewItem Background="LightGray" Foreground="Black" Cont
ent="Tea"
FontFamily="Georgia" FontSize="14" FontWeight="
Bold"></ListViewItem>
<ListViewItem Background="LightBlue" Foreground="Purple"Cont
ent="Orange Juice"
FontFamily="Verdana" FontSize="12" FontWeight="
Bold"></ListViewItem>
<ListViewItem Background="LightGreen" Foreground="Green" Con
tent="Milk"
FontFamily="Georgia" FontSize="14" FontWeight="
Bold"></ListViewItem>
<ListViewItem Background="LightBlue" Foreground="Blue" Conte
nt="Iced Tea"
FontFamily="Verdana" FontSize="12" FontWeight="
Bold"></ListViewItem>
<ListViewItem Background="LightSlateGray" Foreground="Orange
"Content="Mango Shake"
FontFamily="Georgia" FontSize="14" FontWeight="
Bold"></ListViewItem>

The new ListView looks like Figure 4.

Figure 4. Formatted ListView


Displaying Images in a ListView
We can put any controls inside a ListViewItem such as an image and text. To display an
image side by side some text, I simply put an Image and TextBlock control within a
StackPanel. The Image.Source property takes the name of the image you would like to
display in the Image control and TextBlock.Text property takes a string that you would
like to display in the TextBlock.
The following code snippet adds an image and text to a ListViewItem.
<ListViewItem Background="LightCoral" Foreground="Red"
FontFamily="Verdana" FontSize="12" FontWeight="Bold">
<StackPanel Orientation="Horizontal">
<Image Source="coffie.jpg" Height="30"></Image>
<TextBlock Text="Coffie"></TextBlock>
</StackPanel>
</ListViewItem>

After changing my code for all 5 ListViewItems, the ListView looks like Figure 5.

Figure 5. ListViewItems with Image and text


ListView with CheckBoxes
If you put a CheckBox control inside ListViewItems, you generate a ListView control
with checkboxes in it. The CheckBox can host controls within it as well. For instance, we
can put an image and text block as content of a CheckBox.
The following code snippet adds a CheckBox with an image and text to a ListViewItem.
<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>

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"

FontFamily="Georgia" FontSize="14" FontWeight="Bold">


<CheckBox Name="MangoShakeCheckBox">
<StackPanel Orientation="Horizontal">
<Image Source="MangoShake.jpg" Height="30"></Image>
<TextBlock Text="Mango Shake"></TextBlock>
</StackPanel>
</CheckBox>
</ListViewItem>

Now, the new ListView looks like Figure 6.

Figure 6. ListView with CheckBoxes

Data Binding in ListView


The ItemsSource property of ListView is used to bind a collection of IEnuemerable such
as an ArrayList to the ListView control.

The following code snippet creates an ArrayList object.

/// or from a Web service or generate data dynamically

/// <summary>
/// Generate data. This method can bring data from a database or XML
file
/// </summary>
/// <returns></returns>
private ArrayList LoadListViewData()

private void Window_Loaded(object sender, RoutedEventArgs e)

ArrayList itemsList = new ArrayList();


itemsList.Add("Coffie");
itemsList.Add("Tea");
itemsList.Add("Orange Juice");
itemsList.Add("Milk");
itemsList.Add("Mango Shake");
itemsList.Add("Iced Tea");
itemsList.Add("Soda");
itemsList.Add("Water");
return itemsList;
}

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;
}

The collection items are being displayed in Figure 7.

Figure 7. ListView bound to a collection object

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>

<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.Background>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,1" >
<GradientStop Color="RosyBrown" Offset="0.1" />
<GradientStop Color="RoyalBlue" Offset="0.25" />
<GradientStop Color="Bisque" Offset="0.75" />
<GradientStop Color="MediumOrchid" Offset="1.0" />
</LinearGradientBrush>
</TextBox.Background>
<TextBox.Foreground>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,1" >
<GradientStop Color="Orange" Offset="0.25" />
<GradientStop Color="Black" Offset="1.0" />
</LinearGradientBrush>
</TextBox.Foreground>
</TextBox>
The new TextBox looks like Figure 3.

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

The new output looks like Figure 4.

AccessText Control

The AccessText control in WPF converts a character preceded by an underscore to an


Access Key. The Access Key is registered and therefore raises an event when pressed.
This article demonstrates how to create and use an AccessText control in WPF using
XAML and C#.

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).

Resources are two types:


1. Static Resource
2. Dynamic Resource.

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.

DynamicResource: DynamicResources are resolved at runtime. Use DynamicResources when


the value of the resource could change during the lifetime of the Application.

I will show you an example of a Static Resource.

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.

Here I'm using above resources. Have a look at below code.


Syntax is :{ StaticResource x:keyName}
<Grid>
<StackPanel>
<Border Style="{StaticResource background}">
<DockPanel Height="300" Width="500">

<TextBox Style="{StaticResource TitleText}" Height="28" Width="150"> </TextBox>


<Ellipse DockPanel.Dock="Left" HorizontalAlignment="Left" Height="73" Fill="{StaticResour
ce brush}"Width="169"></Ellipse>
<Ellipse DockPanel.Dock="Right" HorizontalAlignment="Right" Width="149" Height="73" Fil
l="{StaticResource forbuttoncolor}"></Ellipse>
</DockPanel>
</Border>
</StackPanel>
</Grid>
Result window looks like this.

In my very next article, I will explain you about Dynamic Resource.

XML Data Binding


WPF provides a number of conveniences in terms of accessing and binding external data
sources. This tutorial shows how you can bind and display XML data using a data template in
XAML. This technique is also known as creating an XML data island.

XML Data Binding


For this example we will create a very simple XAML application that displays a list of favorites
(URLs) from an XML data source. In our XAML document we will define a data source as a
resource and supply that resource with our XML data, in this case a list of URLs. To do this we
will use the XMLDataProvider tag.

<!-- define the XML data source as a resource -->


<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>

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:

You might also like