Friday, May 4, 2007

Resources In WPF

we can reuse objects in XAML by first defining them as Resources .. this is not a .net normal resources. Because that will in the resources file and we can use for storing images , text , etc... and accessed with Uri object. and also it will shipped with executable files or .dll files. Here we are going to write resources inside of XAML or (sometimes in C# code). It will associated with an element or control, page or Window in the application.

Format of Resources:

<SomeType x:Key=”keyname” ...> </SomeType>

Type of Resources :
  • Static Resources
  • Dynamic Resources

Static Resources

XAML elements can reference the resources using the key using markup extension. The particular markup extension you use with resources is named StaticResource.

<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib">
<StackPanel.Resources>
<s:Double x:Key="fontsizeLarge">18.7 </s:Double>
<s:Double x:Key="fontsizeSmall"> 14.7 </s:Double>
</StackPanel.Resources>
<Button HorizontalAlignment="Center" VerticalAlignment="Center" Margin="24">
<Button.FontSize>
<StaticResource ResourceKey="fontsizeLarge" />
</Button.FontSize>
Button with large FontSize
</Button>
<Button HorizontalAlignment="Center" VerticalAlignment="Center" Margin="24" FontSize="{StaticResource fontsizeSmall}" >
Button with small FontSize </Button>
</StackPanel>


Here fontsizeSmall and fontsizeLarge is the static resources. And we have created that resources in element stackpanel. So we can use that resources only child of stackpanel. In case if we declared that resources in window section means we can use anywhere in the single source code. That means insidea of window element.method of accessing static resources .


<Button.FontSize> <StaticResource ResourceKey=”fontsizeLarge”>
</Button.FontSize>
(or)
FontSize=”{StaticResource fontsizeLarge}”

Note:

Forward reference is not allowed in resource reference.We can define control or element as a resource. But we cant use twice. because it will create only one instance.

Creating resources using C# code.
elementname.Resource.Add(“resource name”,value);

Finding Resources
Application.Current.FindResource(key);

Application Resources

we can define resources in the Application file . And we can access those resources from anywhere in the application. For that we need create resources under MyApp.xaml file which is created by the VisulaStudio.

<Application.Resources>
</Application.Resources>

XAML defines a markup extension named x:Static specifically to reference static properties of fields.It also works with enumeration members.

Example :
some static property from a class named MyClass.

<Button.Content>
<x:Static Member=”MyClass:PropertyName” />
</Button.Content>


Dynamic Resource

With StaticResource the key is used to access the object once and the object is retained . When we use the DynamicResource the key is retained and the object is accessed when its needed. The primary purpose of DynamicResource is to access system resources such as colors.

Resources:
if we want share multiple resources among multiple applications. We can use resource dictionary.

Example: SampleResource1.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">;
<LinearGradientBrush x:Key="brushLinear">
<LinearGradientBrush.GradientStops>
<GradientStop Color="Pink" Offset="0" />
<GradientStop Color="Aqua" Offset="1" />
</LinearGradientBrush.GradientStops> </LinearGradientBrush>
</ResourceDictionary>

SampleResource2.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">;
<RadialGradientBrush x:Key="brushRadial"> <RadialGradientBrush.GradientStops>
<GradientStop Color="Pink" Offset="0" />
<GradientStop Color="Aqua" Offset="1" />
</RadialGradientBrush.GradientStops>
</RadialGradientBrush>
</ResourceDictionary>

MyApp.xaml(Application file)

<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" StartupUri="UseCommonResourcesWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="MyResources1.xaml" />
<ResourceDictionary Source="MyResources2.xaml" /> </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>

we can access the resources like this .

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Title="Use Common Resources" Background="{StaticResource brushLinear}">
<Button FontSize="96pt" HorizontalAlignment="Center" VerticalAlignment="Center" Background="{StaticResource brushRadial}">
Button
</Button>
</Window>

Enjoy!!!!!!!!!! If you have a question or you cant get anything in this feel free to comment. I will try to give you as soon as possible.

Tuesday, May 1, 2007

XML DataBinding In WPF

If you have comments, questions or ideas regarding this post content please leave as a comment.

XML DataBinding concept is used to retrieve the data from XML file using XmlDataProvider in XAML language. Windows Presentation Foundation makes it possible to create user interfaces that use data binding wholly in an XML-based markup. When working with XAML we can use the XmlDataProvider object to retrieve XML data and provide it to controls.

Format for Accessing XMLData

XMLDataProvider :

With an XmlDataProvider, the underlying data that can be accessed through data binding in your application can be any tree of XML nodes. In other words, an XmlDataProvider provides a convenient way to use any tree of XML nodes as a binding source. First, we create a XmlDataProvider that will retrieve data asynchronously from the given address and create the data collection with XPath.

XPath :

The XPath properties in WPF are handled by the XmlNode. SelectNodes method. You can modify the XPath queries to get different results. Here are some examples for the XPath query.

  • XPath="Book[1]" - will return the first book element ("XML in Action"). Note that XPath indexes are based on 1, not 0.
  • XPath="Book[@*]" - will return all book elements with any attributes.
  • XPath="Book[last()-1]" - will return the second to last book element ("Introducing Microsoft .NET").
  • XPath="*[position()>3]" - will return all of the book elements except for the first 3.
When you run an XPath query, it returns an XmlNode or a list of XmlNodes. XmlNode is a common language runtime (CLR) object, which means you can use the Path property to bind to the common language runtime (CLR) properties.

Source :

We can specify the xml file source address in source attribute.
(or)
<XmlDataProvider x:Key="BookData" Source="http://MyUrl" Xpath="Books"/>

Example 1:
This sample will help you to get data from external XML file named as BookData.xml and binded with listbox.

BookData.xml

<Books xmlns="">
<Book ISBN="0-7356-0562-9" Stock="in">
<Title>XML in Action</Title>
<Summary>XML Web Technology</Summary>
</Book>
<Book ISBN="0-7356-1370-2" Stock="in">
<Title>Programming Microsoft Windows With C#</Title>
<Summary>C# Programming using the .NET Framework</Summary>
</Book>
<Book ISBN="0-7356-1288-9" Stock="out">
<Title>Inside C#</Title>
<Summary>C# Language Programming</Summary>
</Book>
<Book ISBN="0-7356-1377-X" Stock="in">
<Title>Introducing Microsoft .NET</Title>
<Summary>Overview of .NET Technology</Summary>
</Book>
<Book ISBN="0-7356-1448-2" Stock="out">
<Title>Microsoft C# Language Specifications</Title>
<Summary>The C# language definition</Summary>
</Book>
</Books>


Window1.xaml

<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="410" Height="350" Background="White">
<StackPanel.Resources>
<XmlDataProvider x:Key="BookData" Source="bookdata.xml" XPath="Books"/>

<DataTemplate x:Key="BookDataTemplate">
<TextBlock FontSize="12" Foreground="White">
<TextBlock.Text>
<Binding XPath="Summary"/>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</StackPanel.Resources>
<TextBlock FontSize="18" FontWeight="Bold" Margin="10" HorizontalAlignment="Center">Data From XML</TextBlock>
<ListBox Width="200" Height="300" Background="SteelBlue" ItemsSource="{Binding Source={StaticResource BookData}, XPath=Book}" ItemTemplate="{StaticResource BookDataTemplate}"/>
</StackPanel>


Note :
You can put the Xml file in same location of xaml file. If you have external path means you should specify the path of xml file in source(Ex : Source ="data\bookdata.xml" attribute of XmlDataProvider tag.

Example 2:

This sample will help you to embed directly as an XML data island within the Resources :
In the following example, the data is embedded directly as an XML data island within the Resources section. An XML data island must be wrapped in <x:XData> tags and always have a single root node, which is Inventory in this example.

<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Background="White">
<StackPanel.Resources>
<XmlDataProvider x:Key="InventoryData" XPath="Inventory/Books">
<x:XData>
<Inventory xmlns="">
<Books>
<Book ISBN="0-7356-0562-9" Stock="in" Number="9">
<Title>XML in Action</Title>
<Summary>XML Web Technology</Summary>
</Book>
<Book ISBN="0-7356-1370-2" Stock="in" Number="8">
<Title>Programming Microsoft Windows With C#</Title>
<Summary>C# Programming using the .NET Framework</Summary>
</Book>
<Book ISBN="0-7356-1288-9" Stock="out" Number="7">
<Title>Inside C#</Title>
<Summary>C# Language Programming</Summary>
</Book>
<Book ISBN="0-7356-1377-X" Stock="in" Number="5">
<Title>Introducing Microsoft .NET</Title>
<Summary>Overview of .NET Technology</Summary>
</Book>
<Book ISBN="0-7356-1448-2" Stock="out" Number="4">
<Title>Microsoft C# Language Specifications</Title>
<Summary>The C# language definition</Summary>
</Book>
</Books>
<CDs>
<CD Stock="in" Number="3">
<Title>Classical Collection</Title>
<Summary>Classical Music</Summary>
</CD>
<CD Stock="out" Number="9">
<Title>Jazz Collection</Title>
<Summary>Jazz Music</Summary>
</CD>
</CDs>
</Inventory>
</x:XData>
</XmlDataProvider>
</StackPanel.Resources>

<TextBlock FontSize="18" FontWeight="Bold" Margin="10" HorizontalAlignment="Center">XML Data Source Sample</TextBlock>
<ListBox Width="400" Height="300" Background="SteelBlue">
<ListBox.ItemsSource>
<Binding Source="{StaticResource InventoryData}" XPath="*[@Stock='out'] *[@Number>=8 or @Number=3]"/>
</ListBox.ItemsSource>
<!--Alternatively, you can do the following. -->
<!--<ListBox Width="400" Height="300" Background="Honeydew" ItemsSource="{Binding Source={StaticResource InventoryData}, XPath=*[@Stock\=\'out\'] *[@Number>\=8 or @Number\=3]}">-->

<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock FontSize="12" Foreground="Red"> <TextBlock.Text>
<Binding XPath="Title"/>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>