Thursday, December 11, 2014

Programming Using XAML

XAML Language

This blog discusses the Extensible Application Markup Language (XAML) programming language used to create user interfaces for Windows. XAML was first time introduced as a part of Microsoft .NET Framework 3.5. Officially speaking, XAML is a new descriptive programming language developed by Microsoft to write user interfaces for next-generation managed applications. XAML is used to build user interfaces for Windows and Mobile applications that use Windows Presentation Foundation (WPF) and Windows Runtime. This blog is an introduction to the XAML language. In this blog, we will learn how to define XAML elements, create controls and build screens using XAML Controls. By the end of this chapter, you will be able create user interfaces using XAML.

Purpose of XAML

The purpose of XAML is simple, to create user interfaces using a markup language that looks like XML. Most of the time, you will be using a designer to create your XAML but you’re free to directly manipulate XAML by hand.
A typical user interface developed for Windows has a window or page as a parent container with one or more child containers and other user interface controls. Figure 1 shows a window with file child controls including two Radio Button controls, a Button control, a TextBox control and one TextBlock control.




XAML allows us to represent the parent containers and child controls using markup script elements. Each parent, child containers and child control on the user interface is represented by a XAML element. XAML gives is the flexibility to build user interfaces at both design-time as well as run-time. Design-time usually means using a designer to drag-and-drop, resize and move screen layouts and control positons. Run-time usually means the containers and controls layout positioning is done by the code.

Hello XAML

XAML uses the XML format for elements and attributes. Each element in XAML represents an object which is an instance of a type. The scope of a type (class, enumeration etc.) is defined a namespace that physically resides in an assembly (DLL) of the .NET Framework library. Similar to XML, a XAML element syntax always starts with an open angle bracket (<) and ends with a close angle bracket (>). Each element tag also has a start tag and an end tag. For example, a Button object is represented by the Button object element. The code snippet in Listing 1 represents a Button object element.


The Root Elements

Each XAML document must have a root element. The root element usually works as a container and defines the namespaces and basic properties of the element. Three most common root elements are , , and . The and are other two root elements that can be used in a XAML file.
The Window element represents a Window container. The code snippet in Listing 7 shows a Window element with its Height, Width, Title and x:Name attributes. The x:Name attribute of an element represents the ID of an element used to access the element in the code-behind. The code snippet also sets xmlns and xmlns:x attributes that represent the namespaces used in the code. The x:Class attribute represents the code-behind class name. (<)Window x:Class="HelloXAML.MainWindow" xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml Title="MainWindow" Height="350" Width="525"> Close the Window tag.


The Page element represents a page container. The code snippet in Listing 8 creates a page container. The code also sets the FlowDirection attribute that represents the flow direct of the contents of the page.
Page xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml x:Class="WPFApp.Page1" x:Name="Page" WindowTitle="Page" FlowDirection="LeftToRight" Width="640" Height="480" WindowWidth="640" WindowHeight="480"> Close the Page Tag.


Creating Controls at Run-time

In the previous sections, we created controls at design-time by defining controls in the XAML code. Each XAML element has a corresponding type in .NET Framework that may be used to create and work with a control. For example, the Button type may be used to create and work with a button control. The code listed in Listing 21 creates a button dynamically and sets its properties.

private void CreateControlsDynamically()
{
Button clickButton = new Button();
clickButton.Width = 200;
clickButton.Height = 50;
clickButton.Background = new SolidColorBrush(Colors.Orange);
clickButton.Foreground = new SolidColorBrush(Colors.Black);
clickButton.FontSize = 20;
clickButton.FontWeight = FontWeights.Bold;
clickButton.Name = "HelloButton";
clickButton.Content = "Click Me";
LayoutRoot.Children.Add(clickButton);
}



XAML Collections:


A collection element usually is a parent control with child collection elements. The child collection elements are ItemCollection that implements IList. A ListBox element is a collection of ListBoxItem elements. The code in Listing 1 creates a ListBox with a few ListBoxItems.
ListBox Margin="10,10,0,13" Name="listBox1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="194" Height="200" 
ListBoxItem Content="Coffie"  ListBoxItem 
ListBoxItem Content="Tea"     ListBoxItem 
ListBoxItem Content="Orange Juice"  ListBoxItem 
ListBoxItem Content="Milk"    ListBoxItem 
ListBoxItem Content="Iced Tea"  ListBoxItem 
ListBoxItem Content="Mango Shake"  ListBoxItem 
ListBox



Add Item To List Box:

private void button1_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Add(textBox1.Text);
}



Delete Item From List Box:

private void DeleteButton_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.RemoveAt (listBox1.Items.IndexOf(listBox1.SelectedItem));
}




Data Binding

Before I discuss data binding in general, I must confess, Microsoft experts have made a big mess related to data-binding in .NET 3.0 and 3.5. Instead of making things simpler, they have made them complicated. Perhaps they have some bigger plans for the future but so far I have seen binding using dependency objects and properties, LINQ and DLINQ and WCF and ASP.NET Web Services and it is all a big mess. It’s not even close to the ADO.NET model we had in .NET 1.0 and 2.0. I hope they clean up this mess in near future.

When it comes to data binding, we need to first understand the data. Here is a list of ways a data can be consumed from:

 objects
 a relational database such as SQL Server
 a XML file
 other controls



Data Binding with Objects

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

// Bind ArrayList with the ListBox
LeftListBox.ItemsSource = LoadListBoxData();
private ArrayList LoadListBoxData()
{
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;
}



Data Binding With Database:


Window.Resources
DataTemplate x:Key="listBoxTemplate"
StackPanel Margin="3"
DockPanel
TextBlock FontWeight="Bold" Text="Name:" DockPanel.Dock="Left" Margin="5,0,10,0"
TextBlock Text=" "
TextBlock Text="{Binding ContactName}" Foreground="Green" FontWeight="Bold"
/DockPanel
DockPanel
TextBlock FontWeight="Bold" Text="Address:" Foreground ="DarkOrange" DockPanel.Dock="Left" Margin="5,0,5,0"
TextBlock Text="{Binding Address}" TextBlock Text=", "
TextBlock Text="{Binding City}"
TextBlock Text=", "
TextBlock Text="{Binding Country}"
DockPanel
StackPanel
DataTemplate
Window.Resources


Now we add a ListBox control and set its ItemsSource property as the first DataTable of the DataSet and set ItemTemplate to the resource defined above.

ListBox Margin="17,8,15,26" Name="listBox1" ItemsSource="{Binding Tables[0]}" ItemTemplate="{StaticResource listBoxTemplate}"


Now in our code behind, we define the following variables.

public SqlConnection connection;
public SqlCommand command; string sql = "SELECT ContactName, Address, City, Country FROM Customers";
string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\NORTHWND.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True";



Now on the Windows_Loaded method, we call the BindData method and in the BindData method, we create a connection, data adapter and fill in the DataSet using the SqlDataAdapter.Fill() method.
private void Window_Loaded(object sender, RoutedEventArgs e)
{
BindData();
}
private void BindData()
{
DataSet dtSet = new DataSet();
using (connection = new SqlConnection(connectionString))
{ command = new SqlCommand(sql, connection);
SqlDataAdapter adapter = new SqlDataAdapter();
connection.Open();
adapter.SelectCommand = command;
adapter.Fill(dtSet, "Customers");
listBox1.DataContext = dtSet;
}
}

No comments:

Post a Comment