Silverlight 3 - Populate a ListBox and AutoScroll to an Item

Posted by: Suprotim Agarwal , on 1/31/2010, in Category Silverlight 2, 3, 4 and 5
Views: 37188
Abstract: In this short article, we will see how to populate a ListBox and AutoScroll to a given ListBox item
Silverlight 3 - Populate a ListBox and AutoScroll to an Item
 
In this short article, we will see how to populate a ListBox and AutoScroll to a given ListBox item. We will wire up the ListBox to our Employee class whose definition is as follows.
C#
public int ID { get; set; }
public string FName { get; set; }
public string MName { get; set; }
public string LName { get; set; }
VB.NET
Private privateID As Integer
Public Property ID() As Integer
      Get
            Return privateID
      End Get
      Set(ByVal value As Integer)
            privateID = value
      End Set
End Property
Private privateFName As String
Public Property FName() As String
      Get
            Return privateFName
      End Get
      Set(ByVal value As String)
            privateFName = value
      End Set
End Property
Private privateMName As String
Public Property MName() As String
      Get
            Return privateMName
      End Get
      Set(ByVal value As String)
            privateMName = value
      End Set
End Property
Private privateLName As String
Public Property LName() As String
      Get
            Return privateLName
      End Get
      Set(ByVal value As String)
            privateLName = value
      End Set
End Property
As you can observe, the Employee class has 4 properties (ID, FName, MName, LName). To be able to customize the text in the manner we want, we will create an ItemTemplate and then display the FName and LName fields inside the ListBox.
Note: Although I am not doing any fancy customizations to the text in this example, I still like to use the ItemTemplate because of the customizations it allows you to do.
<UserControl x:Class="SilverlightAutoScroll.MainPage"
    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"
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
    <Canvas>
        <StackPanel Orientation="Vertical" Margin="30 30 0 0">
            <ListBox x:Name="empList" Height="100" Width="300"
                VerticalAlignment="Top" ItemsSource="{Binding Mode=OneWay}">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="{Binding FName}" />
                            <TextBlock Text=" "></TextBlock>
                            <TextBlock Text="{Binding LName}" />
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </StackPanel>
    </Canvas>
</UserControl>
In your code behind, set the DataContext of the ListBox to the List<Employee>
C#
Employee emp;
public MainPage()
{
    InitializeComponent();
    emp = new Employee();
    empList.DataContext = emp.GetEmployeeList();
}
VB.NET
Private emp As Employee
 
Public Sub New()
      InitializeComponent()
      emp = New Employee()
      empList.DataContext = emp.GetEmployeeList()
End Sub
If you run the application at this point of time, the display will be similar to the following:
Output_1
The next task is to add functionality to be able to auto scroll to a desired item. For this purpose, add a textbox and two button controls
<StackPanel Orientation="Horizontal">
<TextBlock Margin="5" Text="Enter a Number"></TextBlock>
<TextBox x:Name="txtIdx" Margin="5" Width="200"></TextBox>
</StackPanel>
<Button x:Name="btnJumpIndex" Content="Jump To Index"
    Click="btnJumpIndex_Click" Margin="5"></Button>
   
<Button x:Name="btnJump" Content="Jump To Last"
    Click="btnJump_Click" Margin="5"></Button>
The first button when clicked, auto scrolls the ListBox to the item number specified in the TextBox. The second button auto scrolls to the last item of the ListBox. Add the following code to the click event of first button, btnJumpIndex_Click
C#
private void btnJumpIndex_Click(object sender, RoutedEventArgs e)
{
    // Add an additional check that string is a valid number
    int idx = Convert.ToInt32(txtIdx.Text);
    int jmpIdx = idx - 1;
    if (empList.Items.Any() && empList.Items.Count > jmpIdx)
    {
        object item = empList.Items.ElementAt(jmpIdx);
        empList.ScrollIntoView(item);
        empList.SelectedItem = item;
    }
}
VB.NET
Private Sub btnJumpIndex_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
      ' Add an additional check that string is a valid number
      Dim idx As Integer = Convert.ToInt32(txtIdx.Text)
      Dim jmpIdx As Integer = idx - 1
      If empList.Items.Any() AndAlso empList.Items.Count > jmpIdx Then
            Dim item As Object = empList.Items.ElementAt(jmpIdx)
            empList.ScrollIntoView(item)
            empList.SelectedItem = item
      End If
End Sub
In the code shown above, we first check if the ListBox has any items and if the index number specified by the user is not more than the number of ListItems. If these two conditions are true, we use the ElementAt() to return the element at a specified index and finally the useful ListBox.ScrollIntoView() method to cause the ListBox to scroll to the specified item. Simple! Here’s the output when the user enters item number ‘13’ and clicks the button
Output_2
Similarly, to be able to auto scroll to the last item, add the following code to the btnJump_Click
C#
private void btnJump_Click(object sender, RoutedEventArgs e)
{
    if (empList.Items.Any())
    {
        object item = empList.Items.Last();              
        empList.ScrollIntoView(item);
        empList.SelectedItem = item;
    }
}
VB.NET
Private Sub btnJump_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
      If empList.Items.Any() Then
            Dim item As Object = empList.Items.Last()
            empList.ScrollIntoView(item)
            empList.SelectedItem = item
      End If
End Sub
Clicking on the ‘Jump to Last’ auto scrolls to the last item in the ListBox
Output_3
If you observe, the scrolling is not very smooth. Instead it just ‘boings’ to the specified item. In one of the forthcoming articles, I will show you how to use the ScrollViewer control to achieve a smooth scrolling effect. The entire source code of this article can be downloaded over here
If you liked the article,  Subscribe to the RSS Feed or Subscribe Via Email.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for ten consecutive times. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by geordie on Friday, May 6, 2011 11:40 AM
problem when you try to do the autoscroll in code behind

private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            object item = empList.Items.ElementAt(12);
            empList.ScrollIntoView(item);
            empList.SelectedItem = item;

        }
fails

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

Tags

JQUERY COOKBOOK

jQuery CookBook