Databinding in Listbox from XML file

In this article we will see how to bind data in listbox from a XML file. The example application I built here will show the data from XML file and how to scroll the data after some time period.
 
The final output will be as shown below:
 
1.gif 
 
Here you can see the article detail coming along with the author image. I have provided two buttons to traverse to the next article description. Otherwise, the details get updated after a certain time frame.
 
Lets us first work on the design part of the control and then we will see the coding part.
 
We have added one listbox and two buttons for this application.
  1. <ListBox x:Name="articleshow" Grid.ColumnSpan="2"   
  2.           Width="484"   
  3.           ScrollViewer.HorizontalScrollBarVisibility="Hidden"     
  4.           ScrollViewer.VerticalScrollBarVisibility="Hidden" ItemTemplate="{StaticResource news1Template1}" ItemsSource="{Binding news1Collection}" Height="222" VerticalAlignment="Top"   
  5.       SelectionChanged="SlideShow_SelectionChanged">  
  6.           <ListBox.Background>  
  7.                    <LinearGradientBrush EndPoint="0.012,0.011" StartPoint="1.003,0.999">  
  8.                              <GradientStop Color="#FFF8F8F8" Offset="0"/>  
  9.                              <GradientStop Color="#FF0265F2" Offset="1"/>  
  10.                    </LinearGradientBrush>  
  11.           </ListBox.Background>  
  12.           <ListBox.ItemContainerStyle>  
  13.                    <Style TargetType="ListBoxItem">  
  14.                              <Setter Property="Width" Value="480"/>  
  15.                              <Setter Property="Height" Value="360"/>  
  16.                    </Style>  
  17.           </ListBox.ItemContainerStyle>  
  18. </ListBox>  
  19. <Button x:Name="Previous" Content="Previous" Canvas.Left="92" Canvas.Top="268" Height="20" Margin="0,0,103,18" VerticalAlignment="Bottom" Click=" Previous_Click" HorizontalAlignment="Right" Width="22" Grid.Column="1" Template="{StaticResource ButtonControlTemplate1}" d:LayoutOverrides="HorizontalAlignment" Cursor="Hand" />  
  20. <Button x:Name="Next" Content="Next" Width="22" Canvas.Left="250" Canvas.Top="268" Height="20" HorizontalAlignment="Right" Margin="0,0,37,18" VerticalAlignment="Bottom" Click="Next_Click" Grid.Column="1" Template="{StaticResource ButtonControlTemplate2}" Cursor="Hand" />  
Now let us style the button.
  1. <ControlTemplate x:Key="ButtonControlTemplate1" TargetType="Button">  
  2.           <Grid>  
  3.                    <VisualStateManager.VisualStateGroups>  
  4.                              <VisualStateGroup x:Name="FocusStates">  
  5.                                       <VisualState x:Name="Focused"/>  
  6.                                       <VisualState x:Name="Unfocused"/>  
  7.                              </VisualStateGroup>  
  8.                              <VisualStateGroup x:Name="CommonStates">  
  9.                                       <VisualState x:Name="Normal"/>  
  10.                                       <VisualState x:Name="MouseOver"/>  
  11.                                       <VisualState x:Name="Pressed"/>  
  12.                                       <VisualState x:Name="Disabled"/>  
  13.                              </VisualStateGroup>  
  14.                    </VisualStateManager.VisualStateGroups>  
  15.                    <Canvas Background="#FF060606">  
  16.                              <Path x:Name="arrow" Stroke="#FFE3FA06" StrokeThickness="3" Height="18.346" Margin="0,0,0,0" Width="16.686" RenderTransformOrigin="0.5,0.5" Data="M 1,1.5 L 4.5,5 L 8,1.5" UseLayoutRounding="False" Canvas.Left="2.907" Canvas.Top="0.327" Stretch="Fill">  
  17.                                       <Path.RenderTransform>  
  18.                                                 <TransformGroup>  
  19.                                                           <ScaleTransform/>  
  20.                                                           <SkewTransform/>  
  21.                                                           <RotateTransform Angle="88.93"/>  
  22.                                                           <TranslateTransform/>  
  23.                                                 </TransformGroup>  
  24.                                       </Path.RenderTransform>  
  25.                              </Path>  
  26.                    </Canvas>  
  27.           </Grid>  
  28. </ControlTemplate>  
The above XAML code is only for one button. Same is the code for other button.
 
Now let us see how to bind data in listbox from XML.
 
The xml for this application is:
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <news>  
  3.   <news1 newsid="1" newstitle="Introduction of SPPersistedObject class" newsimage="Images/dhananjaycoder.jpg" newsdesc="In this article, I will give a high level introduction of SPPersistedObject class and its uses. I will give one sample also to explain uses of this class."/>  
  4.   <news1 newsid="2" newstitle="Filtered TextBox in Silverlight 3" newsimage="Images/dpatra.jpg" newsdesc="In this article we will see how we can filter a Textbox on Keyboard inputs. "/>  
  5.   <news1 newsid="3" newstitle="Charting in Silverlight" newsimage="Images/mahesh.jpg" newsdesc="This tutorial demonstrates how to use charting applications in Silverlight using Silverlight Toolkit. First you will learn how to get started with the Silverlight Toolkit and then create bar chart, line chart, pie chart, column chart, and scatter chart in a Silverlight application."/>  
  6.   <news1 newsid="4" newstitle="Accordion Control in Silverlight 3" newsimage="Images/prv_new.jpg" newsdesc="In this article I will show you how to design the Accordion Control in Silverlight 3."/>  
  7. </news>  
Now in expression blend open the "data" tab and select "Import sample data from XML".
 
2.gif 
 
In the above screen select the XML file from the location and press OK.
 
A new data source will be added to your application.
 
3.gif 
 
Now to bind this data source to our listbox. Drag it to listbox.
 
4.gif 
 
We will have the following XAML code for listbox.
  1. <ListBox Height="100" Margin="14.5,0,-19,-169" VerticalAlignment="Bottom" Grid.Column="1" Grid.Row="1" DataContext="{Binding}" ItemTemplate="{StaticResource news1Template}" ItemsSource="{Binding news1Collection}"/>  
The ItemTemplate code is as follows:
  1. <DataTemplate x:Key="news1Template">  
  2.           <StackPanel>  
  3.                    <TextBlock Text="{Binding newsdesc}"/>  
  4.                    <TextBlock Text="{Binding newsid}"/>  
  5.                    <Image Source="{Binding newsimage}" HorizontalAlignment="Left" Height="64" Width="64"/>  
  6.                    <TextBlock Text="{Binding newstitle}"/>  
  7.           </StackPanel>  
  8. </DataTemplate>  
We are now going to edit the ItemTemplate.
 
5.gif 
 
Right click the listbox and select the options shown in the above figure.
 
The below screen shows the default style of the ItemTemplate.
 
6.gif 
 
After some changes to my ItemTemplate code will be as follows:
  1. <DataTemplate x:Key="news1Template1">  
  2.                    <Canvas Margin="0,0,-251,143" Background="#FFF4F7F8" x:Name="can1" Width="473">  
  3.                              <TextBlock Text="{Binding newsdesc}" Width="312" Canvas.Left="153" Canvas.Top="75" Height="57" TextWrapping="Wrap"/>  
  4.                              <Image Source="{Binding newsimage}" HorizontalAlignment="Left" Width="100" Height="180" Canvas.Left="26" Canvas.Top="28">  
  5.                                       <Image.Effect>  
  6.                                                 <DropShadowEffect Color="#FF042DF9" BlurRadius="10"/>  
  7.                                       </Image.Effect>  
  8.                              </Image>  
  9.                              <TextBlock Text="{Binding newstitle}" Width="312" Canvas.Left="153" Canvas.Top="28" FontWeight="Bold" FontSize="13.333" FontFamily="Verdana" Foreground="#FF0C41F8"/>  
  10.                              <Rectangle Fill="#FF2F4386" Stroke="Black" Height="24" Width="473"/>  
  11.                              <TextBlock Height="20" Width="144" Canvas.Left="4" Canvas.Top="2" FontSize="13.333" FontWeight="Bold" Foreground="#FFEEFA06" Text="Featured Article" TextWrapping="Wrap"/>                                              
  12.                   </Canvas>  
  13. </DataTemplate>  
That's all for the XAML part of the code.
 
The code behind for the two button is as shown below:
  1. private void Next_Click(object sender, RoutedEventArgs e)  
  2. {  
  3.     articleshow.SelectedIndex++;  
  4.     articleshow.ScrollIntoView(articleshow.SelectedItem);  
  5. }  
  6. private void Previous_Click(object sender, RoutedEventArgs e)  
  7. {  
  8.       articleshow.SelectedIndex--;  
  9.       articleshow.ScrollIntoView(articleshow.SelectedItem);  
  10. }  
For automatic change of the content I use the DispatcherTimer class from the System.Windows.Threading namespace. The code will be as follows:
  1. public MainPage()  
  2. {  
  3.     // Required to initialize variables  
  4.     InitializeComponent();  
  5.     DispatcherTimer dt = new DispatcherTimer();     
  6.     dt.Interval = new TimeSpan(0, 0, 0, 0, 5000);              
  7.     dt.Tick += new EventHandler(news_change);     
  8.     dt.Start();  
  9. }  
  10. void news_change(object sender, EventArgs e)     
  11. {  
  12.           articleshow.SelectedIndex++;  
  13. }  
Download the source code to know about its working.
 
That's it. Happy coding!


Similar Articles
MCN Solutions Pvt. Ltd.
MCN Solutions is a 17 year old custom software development and outsourcing services provider.