Monday, March 1, 2010

Using ListBox instead of ScrollViewer in Silverlight

If you are thinking about scrolling image or text in silverlight, ScrollViewer might be the first thing to pop up in head. However, it is not always works.

In my scenario, there is an auction-related project. It basically use silverlight to create UI similarly as below,


The left Viewer is the connection and biding information. The right one is the DataGrid displaying the latest price for each items.


In .xaml file, I was using ScrollViewer,
 <ScrollViewer Margin="25,0,-7,8" x:Name="connectViewer">
                <TextBlock x:Name="lblMessages" Margin="1" TextWrapping="Wrap" Height="860" FontSize="8"></TextBlock>
            </ScrollViewer>

           
In code behind,
lblMessages.Text += message + Environment.NewLine;

The problem is there is a limitation in the length of TextBlock. Because there are so many biding information which reach the limit of TextBlock, the new coming biding info won't be displayed in ScrollViewer.


Solution:
Use ListBox DataTemplate intead.

Code in .xaml
 <ListBox x:Name="listBoxConnectInfo" Margin="25,0,-7,8">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding}" TextAlignment="Left" />
                    </DataTemplate>
                </ListBox.ItemTemplate>
 </ListBox>

In code behind,
listBoxConnectInfo.Items.Add(message);

So for every each time, it adds a TextBlock into ListBox and bind the message to the Text property.The more important thing is, it is scrollable as well.


Hope that helps -:).
Please don't hesitate to leave comments if you have better idea.

No comments:

Post a Comment