Sss
Sss

Reputation: 1529

How to Create Scrollbar for a ListBox in C#

I am using silverlight and coding in c# and i have to create a scrollbar on a list displayed.

Currently the list is displayed without scrollbar but it should contain one scrollbar as well.

My code to display the List is:

ListBox lines = new ListBox(); 
ScrollViewer scrollViewer = new ScrollViewer();            
scrollViewer.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
lines.ItemsSource = param.Component.Attributes.Items;
Grid.SetColumn(lines, 1);
Grid.SetRow(lines, LoopCount);
childGrid.Children.Add(lines);

lines.SelectedIndex = 0;
lines.SelectedItem = param.Component.Attributes.Items;
lines.SelectionChanged += new SelectionChangedEventHandler(List_SelectionChanged);
lines.SelectedIndex = lines.Items.Count - 1;

"lines" variable contains my ListBox and i tried to achieve it throught scrollViewer but i dont know how to proceed further. (Please note that i have to create selection changed event on selecting the items on GUI displayed on button click) so the code for scrollbar must not influence that procedure. And i have to code in c# only not in xaml. Thanks in advance for the help.

Upvotes: 0

Views: 505

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222522

When you are puttig items Inside ScrollViewer You need to set the Content of ScrollViewer to ListBox,

change your code like below,

//Create ScrollViewer which is a child of Grid
var scroll = new ScrollViewer();
//add to the grid
childGrid.Children.Add(scroll);
//create lisbox and set it to the content of scrollviewer which is a Child of ScrollViewer
var listBox = new ListBox();
scroll.Content = listBox;        

Upvotes: 1

Related Questions