Tag Archives: wpf

Create Checked List Box in WPF C#


Checked List box is the combination of Text and Check box. In the C# tool box you have Listbox and Combo box , not the checked listbox.

The Data template become the savior for you. We can create a Data Template for our List box.

In fact Data template can be used to customize the look and feel of the listbox items, what ever you wish.

Let’s add a Simple ListBox with Check box using XAML code which bind the Product List

<ListBox Style="{DynamicResource prent_and_groups_List}"   Background="LightGreen" SelectedItem="SlectedAccount" ItemsSource="{Binding Products}"   Grid.Row="1" Grid.Column="1"  Grid.RowSpan="2" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <CheckBox IsChecked="{Binding Ischecked}" Content="{Binding Name}" />
                </DataTemplate>
            </ListBox.ItemTemplate>
            
        </ListBox>

C# WPF – Custom Observable String Dictionary for Binding


Observable collection objects come handy when you dealing with Binding controls with values in WPF and C#.Net.

Dictionary object help you to build a collection values using a single dictionary with key, value pair.

With both we can build a custom class for binding and dynamically updated collection, which can be used for multiple purposes, around your projects.

The root : Observable Dictionary

// The orginal class was obtained from official site, then I made some desirable changes such as `UpdateOrAdd`,
// which I think usefull for others
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
namespace mynamespace
{
class ObservableDictionary : IDictionary<string, string>, INotifyPropertyChanged
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
/// <summary>
/// Creates a ContentLocatorPart with the specified type name and namespace.
/// </summary>
public ObservableDictionary()
{
_nameValues = new Dictionary<string, string>();
}
#endregion Constructors
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Adds a key/value pair to the ContentLocatorPart. If a value for the key already
/// exists, the old value is overwritten by the new value.
/// </summary>
/// <param name="key">key</param>
/// <param name="val">value</param>
/// <exception cref="ArgumentNullException">key or val is null</exception>
/// <exception cref="ArgumentException">a value for key is already present in the locator part</exception>
public void Add(string key, string val)
{
if (key == null || val == null)
{
throw new ArgumentNullException(key == null ? "key" : "val");
}
_nameValues.Add(key, val);
FireDictionaryChanged();
}
/// <summary>
/// Removes all name/value pairs from the ContentLocatorPart.
/// </summary>
public void Clear()
{
int count = _nameValues.Count;
if (count > 0)
{
_nameValues.Clear();
// Only fire changed event if the dictionary actually changed
FireDictionaryChanged();
}
}
public void UpdateOrAdd(string key,string value)
{
if (ContainsKey(key) == false)
{
Add(key, value);
}
else
{
Remove(key);
Add(key, value);
}
}
/// <summary>
/// Returns whether or not a value of the key exists in this ContentLocatorPart.
/// </summary>
/// <param name="key">the key to check for</param>
/// <returns>true - yes, false - no</returns>
public bool ContainsKey(string key)
{
return _nameValues.ContainsKey(key);
}
/// <summary>
/// Removes the key and its value from the ContentLocatorPart.
/// </summary>
/// <param name="key">key to be removed</param>
/// <returns>true - the key was found in the ContentLocatorPart, false o- it wasn't</returns>
public bool Remove(string key)
{
bool exists = _nameValues.Remove(key);
// Only fire changed event if the key was actually removed
if (exists)
{
FireDictionaryChanged();
}
return exists;
}
/// <summary>
/// Returns an enumerator for the key/value pairs in this ContentLocatorPart.
/// </summary>
/// <returns>an enumerator for the key/value pairs; never returns null</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return _nameValues.GetEnumerator();
}
/// <summary>
/// Returns an enumerator forthe key/value pairs in this ContentLocatorPart.
/// </summary>
/// <returns>an enumerator for the key/value pairs; never returns null</returns>
public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
{
return ((IEnumerable<KeyValuePair<string, string>>)_nameValues).GetEnumerator();
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException">key is null</exception>
public bool TryGetValue(string key, out string value)
{
if (key == null)
throw new ArgumentNullException("key");
return _nameValues.TryGetValue(key, out value);
}
/// <summary>
///
/// </summary>
/// <param name="pair"></param>
/// <exception cref="ArgumentNullException">pair is null</exception>
void ICollection<KeyValuePair<string, string>>.Add(KeyValuePair<string, string> pair)
{
((ICollection<KeyValuePair<string, string>>)_nameValues).Add(pair);
}
/// <summary>
///
/// </summary>
/// <param name="pair"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException">pair is null</exception>
bool ICollection<KeyValuePair<string, string>>.Contains(KeyValuePair<string, string> pair)
{
return ((ICollection<KeyValuePair<string, string>>)_nameValues).Contains(pair);
}
/// <summary>
///
/// </summary>
/// <param name="pair"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException">pair is null</exception>
bool ICollection<KeyValuePair<string, string>>.Remove(KeyValuePair<string, string> pair)
{
return ((ICollection<KeyValuePair<string, string>>)_nameValues).Remove(pair);
}
/// <summary>
///
/// </summary>
/// <param name="target"></param>
/// <param name="startIndex"></param>
/// <exception cref="ArgumentNullException">target is null</exception>
/// <exception cref="ArgumentOutOfRangeException">startIndex is less than zero or greater than the lenght of target</exception>
void ICollection<KeyValuePair<string, string>>.CopyTo(KeyValuePair<string, string>[] target, int startIndex)
{
if (target == null)
throw new ArgumentNullException("target");
if (startIndex < 0 || startIndex > target.Length)
throw new ArgumentOutOfRangeException("startIndex");
((ICollection<KeyValuePair<string, string>>)_nameValues).CopyTo(target, startIndex);
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Operators
//
//------------------------------------------------------
//------------------------------------------------------
//
// Public Events
//
//------------------------------------------------------
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region Public Properties
/// <summary>
/// The number of name/value pairs in this ContentLocatorPart.
/// </summary>
/// <value>count of name/value pairs</value>
public int Count
{
get
{
return _nameValues.Count;
}
}
/// <summary>
/// Indexer provides lookup of values by key. Gets or sets the value
/// in the ContentLocatorPart for the specified key. If the key does not exist
/// in the ContentLocatorPart,
/// </summary>
/// <param name="key">key</param>
/// <returns>the value stored in this locator part for key</returns>
public string this[string key]
{
get
{
if (key == null)
{
throw new ArgumentNullException("key");
}
string value = null;
_nameValues.TryGetValue(key, out value);
return value;
}
set
{
if (key == null)
{
throw new ArgumentNullException("key");
}
if (value == null)
{
throw new ArgumentNullException("value");
}
string oldValue = null;
_nameValues.TryGetValue(key, out oldValue);
// If the new value is actually different, then we add it and fire
// a change notification
if ((oldValue == null) || (oldValue != value))
{
_nameValues[key] = value;
FireDictionaryChanged();
}
}
}
/// <summary>
///
/// </summary>
public bool IsReadOnly
{
get
{
return false;
}
}
/// <summary>
/// Returns a collection of all the keys in this ContentLocatorPart.
/// </summary>
/// <value>keys</value>
public ICollection<string> Keys
{
get
{
return _nameValues.Keys;
}
}
/// <summary>
/// Returns a collection of all the values in this ContentLocatorPart.
/// </summary>
/// <value>values</value>
public ICollection<string> Values
{
get
{
return _nameValues.Values;
}
}
#endregion Public Properties
//------------------------------------------------------
//
// Public Events
//
//------------------------------------------------------
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
//------------------------------------------------------
//
// Internal Operators
//
//------------------------------------------------------
//------------------------------------------------------
//
// Internal Events
//
//------------------------------------------------------
#region Public Events
/// <summary>
///
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
#endregion Public Events
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
/// <summary>
/// Notify the owner this ContentLocatorPart has changed.
/// </summary>
private void FireDictionaryChanged()
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(null));
}
}
#endregion Private Methods
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
/// <summary>
/// The internal data structure.
/// </summary>
private Dictionary<string, string> _nameValues;
#endregion Private Fields
}
}

Our class utilizes two interphases namely Dictionary and INotifyPropertyChanged. The INotifyPropertyChanged and the implemented methods help use to update the data source where the object is binded. As a result when ever the object updated with new values, the control automatically updates.

How to use

Drop the class file to your solution and create an object of our class and also add some values to the dictionary as follows

ObservableDictionary _items = new ObservableDictionary();
_items.UpdateOrAdd("Dev", "Manoj");
_items.UpdateOrAdd("Lan", "C#");
tbl_lan.DataCOntext=_items;
tbl_lan.DataCOntext=_items;

xaml

 <TextBlock x:Name="tbl_dev" TextAlignment="Left" HorizontalAlignment="Left" Text="{Binding [Dev]}" Foreground="LightGoldenrodYellow" />
 <TextBlock x:Name="tbl_lan" TextAlignment="Left" HorizontalAlignment="Left" Text="{Binding [Lan]}" Foreground="LightGoldenrodYellow" />        

Go head and customize the class to meet your requirements

Storyboard animation in WPF C#


WPF allows you to customize the look and feel using XAML and Styles, it allow capable of create some cool animation which is a way of interacting with user and UI. You can use Storyboard with EvenTrigger.

Let’s create a style for a textbox control, which add some color, align text etc ,then add a Style trigger and Event trigger which also add some font animation , want to play while the textbox has focus and lost it’s focus.

The Style

It is a simple style, add font, alignment etc Name the style as NuberTex.

 <Style x:Key="NumberText" TargetType="TextBox">
        <Setter Property="FontSize" Value="18"/>
        <Setter Property="TextAlignment" Value="Right"/>   
        

  </Style>    

To use this style add the following lines to the TextBox control (xaml).

 <TextBox  Style="{DynamicResource NumberText}" />

Storyboard

Now we can add a Event trigger and a story board to the above style. First we create a style trigger and then we want to add some style based on Events, namely Gotfocus and Lostfocus.

<Style.Triggers >
            <Trigger Property="IsFocused" Value="True">
                <Setter Property="Foreground" Value="IndianRed"/>
            </Trigger>
            <EventTrigger RoutedEvent="GotFocus">
                <EventTrigger.Actions>
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimation Duration="0:0:0:1" To="20" Storyboard.TargetProperty="FontSize" From="18"  />
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger.Actions>
            </EventTrigger>
            
            <EventTrigger RoutedEvent="LostFocus">
                <EventTrigger.Actions>
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimation Duration="0:0:0:1" From="20" Storyboard.TargetProperty="FontSize" To="18"  />
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger.Actions>
            </EventTrigger>
            
        </Style.Triggers>

The storyboard is added within the trigger action. We used a double animation which increase the font from range of values specified using To and From, you can specify what event property you want to play using Target property.

Complete Style

Here is the full style

<Style x:Key="NumberText" TargetType="TextBox">
        <Setter Property="FontSize" Value="18"/>
        <Setter Property="TextAlignment" Value="Right"/>         
        
        <Style.Triggers >
            <Trigger Property="IsFocused" Value="True">
                <Setter Property="Foreground" Value="IndianRed"/>
            </Trigger>
            <EventTrigger RoutedEvent="GotFocus">
                <EventTrigger.Actions>
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimation Duration="0:0:0:1" To="20" Storyboard.TargetProperty="FontSize" From="18"  />
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger.Actions>
            </EventTrigger>
            
            <EventTrigger RoutedEvent="LostFocus">
                <EventTrigger.Actions>
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimation Duration="0:0:0:1" From="20" Storyboard.TargetProperty="FontSize" To="18"  />
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger.Actions>
            </EventTrigger>
            
        </Style.Triggers>

    </Style>    

Add a alternate color to ListView rows in WPF using XAML


Using Alteration count you can add Datagrid like alternate background for ListViewItems. There is no alternate background property for ListView control in WPF, instead we can made this possible with style triggers.

Style triggers work with property and we can track the change with trigger value value.

Styles

The alternate color we want to apply is for ListViewItems , so we have to create a Itemcontainer style for ListView as follows.

    <Style TargetType="ListViewItem" x:Key="gridview_itemcontainer1" >
        <Setter Property="Foreground" Value="DarkBlue"/>
        <Setter Property="FontSize" Value="13.5"/>       
    </Style>

You can define the style as resource file or can define as ListView.Resources in your xaml portion of UI.

As ListViewResource

<ListView AlternationCount=2 >
  <ListView.Resources>
   <Style TargetType="ListViewItem" >
        <Setter Property="Foreground" Value="DarkBlue"/>
        <Setter Property="FontSize" Value="13.5"/>       
    </Style>
  </ListView.Resources>

<ListView/>

In our style we are define background and font using Setter. Likewise we can add some Style Triggers. We want to change the color of ListViewItems according to the AlternationIndex value.

Style.Triggers

Add the following style trigger section in our style.

<Style.Triggers>
    <Trigger Property="ItemsControl.AlternationIndex" Value="0">
       <Setter Property="Background" Value="LightBlue"></Setter>
    </Trigger>
    <Trigger Property="ItemsControl.AlternationIndex" Value="1">
       <Setter Property="Background" Value="LightYellow"></Setter>
    </Trigger>
 </Style.Triggers>

We had added two trigger for checking the alternationIndex value and a associated setter for setting background property of ListViewItem.

Our style is finished and purpose is served.

If you are use resource file you can assign the style to Item container as ItemContainerStyle=”{DynamicResource <RESOURCEKEY>}”. Replace the RESOURCE KEY with your own style key.

How to use common folder paths in C#


Reading files from application path may be one of key requirement of any application. Actually we can place many place you love to have, on a installation machine there can be restriction as well.

Like wise in a Windows system, installer may want to put apps and other files to Programfiles. This folder intended to work with executable,configuration files etc. You can’t programmatically create new folder or files in Programfiles folder, which may require some admin rights. So where we kept those documents and other data ?

It is wise to store such files on Application data folder or even on your Document folder. For reports and other stuffs Document folder is enough.

Access Special Folders

We can use the Enironment.SpecialFolder to access the App data and Documents and also can fetch path to those folders using GetFolderPath method of Environment class.

datapath = Environment.GetFolderPath(Environment.SpecialFolder
.ApplicationData);
reportPath = Environment.GetFolderPath(Environment.
SpecialFolder.MyDocuments);

the first line will get the location of C:\Users\manoj\AppData\Roaming and the second will show the Document folder path .

Access application path

How to access application/executable path in C#. This can be done using Application.ExecutablePath and the GetFolderPath method

 Path.GetDirectoryName(Application.ExecutablePath);

Convert Doc file to PDF,XPS,SVG,XML,HTML using Spire in C#


There are many useful libraries around Nuget which can be made your application more productive. We already learned how to create PDF files from a Word Document using Interop and Docx.

Free Spire.Doc offer high performance operation on word documents. You can check the project on Codeplex Achive

Spire offer following feature

  • *Convert Word to PDF
  • *Convert Word to HTML
  • *Convert Word to Image
  • *Convert Word to XML
  • *Convert Word to RTF
  • *Convert Word to EMF
  • *Convert Word to¬†XPS

How to Convert Doc to PDF

Add the library to your project using Nuget Package Manager

Visual Studio 2019 : Nuget Package Manager

Create aggregate function using lambda expressions on collectionView in C#


Hope you need this article for updating your skills. As we seen in the last article, we learned about collection view and how to create filters using them. If you miss just take a look at it. To I will help you learn som lambda expression

Lambda experession ?

Lambda expressions permit the creation of anonymous functions with a very concise syntax. I don’t want explain what lambda expression is , I will show you how to use it. For learn more about lambda please visit Richard Carr’s lackwaspBlog ,he had a detailed guide to lambda.

The following is an example of lambda expression.

(params) => expression

let’s jump into the regular salesinformation example. The sales Collection used to store all sales information such as Customer,Date,Amount,tax,discount etc. It may contain many of them, that is why we used collection or List.

We are going to use Agrgregate feature of collectionview object to create lambda function, for find total sale amount ,tax collected etc

 var total_saleAmount = Salescolletionview.Cast<SalesView>()
.Aggregate<SalesView, double>(0, (totalSale, s) => totalSales += s.Amount);

The SaleCollectionView class Hold information about Sales which is in the type of ViewClass. So first up all we can cast the view to SalesView and then invoke Aggregate. The Aggregate functionality of C#.Net let us create anonymous function using lambda expression.

At first we had initialise the output variable and access the Amount property of viewclass and then add it up.

In the similar manner you can operate on other properties of view class.

 var total_tax = Salescolletionview.Cast<SalesView>().
Aggregate<SalesView, double>(0, (tax, s) => tax+= s.Tax);

C#Tips/Tricks – XAML Formating


Do you know , within XAML element of you C# WPF application , the binded data can be formated using string format. For a date field you can use the following style

<TextBlock x:Name="tbl_fy" Text="{Binding [0].f_date1,
 StringFormat={}{0:MMM/dd/yyyy}}" Foreground="Beige"
 FontSize="14" Width="119"/>   

WPF: Observable collections for dynamic itemsource


ObservableColeection is ObjectModel collection which can be used to store and l list of objects in .Net. One of the notable feature of this collection is that unlike other collection it can be automatically update itemsources.

Observablecollection implements IObservable Interface

C# ObjectModel collection

Where to use Observable

Observable can be best fit where keep need to observe changing objects. The best example was a registration of student and throught the application you have to access the names, when ever a new registration occurs names should be available without any refresh in all other modules like, on studentmanagement,on fee collection,on attendance etc.

Observable collection aware change in items only when you do add new item, or delete / modify items in the collection.

Followiing example store and modify student scores and dynamically add to a datagrid.

The XAML

<Window x:Class="WpfApp2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp2"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="192*"/>
            <RowDefinition Height="227*"/>
        </Grid.RowDefinitions>
        <Button Click="Button_Click" Content="Add" HorizontalAlignment="Left" Height="64" Margin="26,28,0,0" VerticalAlignment="Top" Width="258"/>
        <Button Content="Clear" Click="Button_Click_1" HorizontalAlignment="Left" Height="72" Margin="26,110,0,0" VerticalAlignment="Top" Width="258"/>
        <Button Content="New Set" HorizontalAlignment="Left" Height="81" Margin="26,0,0,0" Grid.Row="1" VerticalAlignment="Top" Width="258" Click="Button_Click_3"/>
        <DataGrid ItemsSource="{Binding}" x:Name="resultgrid" HorizontalAlignment="Left" Height="245" Margin="344,28,0,0" Grid.RowSpan="2" VerticalAlignment="Top" Width="418"/>
    </Grid>
</Window>

The above code simply bind the grid with itemsource. Have a look at the c# source code.

ObserVableCollection : example

ViewClass

 class Result
    {
        public string sname { get; set; }
        public string grade { get; set; }
        public decimal mark { get; set; }
    }

We are creating a set of objects and create collection of objects and add and modify the collection.

Code behind the collection data

 public partial class MainWindow : Window
    {
        ObservableCollection<Result> studentset = new ObservableCollection<Result>();
        public MainWindow()
        {
            InitializeComponent();
            resultgrid.ItemsSource = studentset;            
            }
       private void Button_Click(object sender, RoutedEventArgs e)
        {

            Result mark;
            mark = new Result() { sname = "Abraham", grade = "A+", mark = 95 };
            studentset.Add(mark);
            mark = new Result() { sname = "Muhammed", grade = "B", mark = 95 };
            studentset.Add(mark);
            mark = new Result() { sname = "Nikhil", grade = "A", mark = 95 };
            studentset.Add(mark);            
        }
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            studentset.Clear();
        }
        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
          Result  mark = new Result() { sname = "John", grade = "A", mark = 95 };
            studentset.Add(mark);
        }
    }

Each time an element to the collection were added , the itemsource is being updated and refreshed.

In my experience Observable collection is best suited for report objects, when ever a new item is added to the report collection your report is being updated, it is like you have a live reporting system.

Tip : You can create Method for adding only new items to the collection instead of removing all of them using Remove method of collection class.

WPF: DataTemplate for handling multiple set data


With the help of XAML you can almost change each and every element in your WPF Window UI. Using the templating system you can overload the existing behaviour of control and can apply to other control you were adding . So do onece and reuse later that’s what template and style says.

As name indicate DataTemplate in WPF handles data set. Lets come to our example , I have two type of datas which want to show in customized listbox with images and text.

  • One shows recently added vouchers
  • Another shows list Tasks todo, which is repeating task.
List with Item Template

This can be done with two list boxes as we know, but I can use DataTemplate to design the items and change the look and feel of the items in the list box.

We can create template and styles inside forms XAML inside <Windows.Resources> tag or can place it seperate xaml , so that you can use them throug out your WPF project.

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        Your template Goes Here
    </Window.Resources>
    <Grid>
        
    </Grid>
</Window>

Design the Item Template

Let’s create a item template for showing recent vouchers first, with a grid layout and add Textblock controls and a image controls to show data.

  <DataTemplate x:Key="tr_History">
        <Border x:Name="border" BorderBrush="LightSlateGray" BorderThickness="1" Background="AliceBlue"
          Padding="5" Margin="0">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="20"/>
                    <RowDefinition Height="20"/>
                    <RowDefinition Height="20"/>
                    <RowDefinition/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition  Width="40"/>
                    <ColumnDefinition Width="93" />
                     
                </Grid.ColumnDefinitions>
                <Image Source="images/027.png" Grid.Column="0" Grid.Row="0"/>
                <TextBlock FontSize="13" Grid.Row="0" Grid.Column="1" HorizontalAlignment="Right" Foreground="DarkGreen" Text="{Binding eno}" />
                <Image Source="images/calendar.png" Grid.Column="0" Grid.Row="1"/>
                <TextBlock FontSize="13" Grid.Row="1" Grid.Column="1" HorizontalAlignment="Right" Foreground="DarkGreen" Text="{Binding edate, StringFormat=\{0:dd/MM/yyyy\}}"/>
                <Image Source="images\Money-icon.png" Grid.Column="0" Grid.Row="2"/>
                <TextBlock FontSize="13" Grid.Row="2" Grid.Column="1" HorizontalAlignment="Right" Foreground="DarkGreen" Text="{Binding amount, StringFormat=\{0:0.00\}}"/> 
                 
            </Grid>
        </Border>
    </DataTemplate>

We binded the edate,amount and eno with Textblock control. In xaml attach the itemtemplate as follows

<ListBox  HorizontalContentAlignment="Stretch" ItemTemplate="{StaticResource 
ResourceKey=tr_History}"  Background="White" x:Name="lst_tasks" DataContext="{Binding}" 
ItemsSource="{Binding}"  Margin="0,65,11,0" HorizontalAlignment="Right" Width="176" 
Height="210" VerticalAlignment="Top"/>

And in the code I colleccted the data using Linq as a List and bind its Itemsource as follows

var list = (from r in public_members.receipts.AsEnumerable()
                                        where (r.Field<int>("r_no") != int.Parse(txt_rno.Text.ToString()) && r.Field<decimal>("r_cr_ledger") == crid)
                                        select new { eno = r.Field<int>("r_no"), edate = r.Field<DateTime>("r_date"), amount = r.Field<decimal>("r_cramount") });

                            tr_history_list.ItemsSource = list;

The Task Template

The second template I want to create have similar nature but data will be different one

  <DataTemplate x:Key="Tasks">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="23"/>
                <RowDefinition Height="24"/>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="40" />
                <ColumnDefinition />
            </Grid.ColumnDefinitions>
            <Image   Source="images/onebit_20.png"   Grid.Column="0" Grid.Row="0"   />
            <TextBlock   FontSize="13"  Grid.Row="0" Grid.Column="1" Text="{Binding TAGS}" VerticalAlignment="Center"  />
            <Image   Source="images/money.png"    Grid.Column="0" Grid.Row="1" Width="25" Height="25"/>
            <TextBlock FontSize="13"   Grid.Row="1" Grid.Column="1" Text="{Binding TASK_AMOUNT,  StringFormat=\{0:0.00\}}" VerticalAlignment="Center" />

        </Grid>
    </DataTemplate>

Here I binded the TAGS,TASK_ANOUNT to Textblocks. Infact you can design different layour as you like. It need not be the same.

How to change ItemTemplate @ run time

We have learned how to add a item layout in the first template example, now we want to switch between those two layout when it requires. Todo this we need delcare and Template variable and Find our Templates using FindResources command.

 lst_tasks.ItemsSource = list;
DataTemplate pre = this.FindResource("tr_History2") as DataTemplate;
lst_tasks.ItemTemplate = pre;

You can swithch to the second template similar manner.

 lst_tasks.ItemsSource = list;
DataTemplate pre = this.FindResource("Task") as DataTemplate;
lst_tasks.ItemTemplate = pre;

If you have any question please leave a comment.