Friday, November 23, 2012

Scrollable Textbox Silverlight/WP7

I was doing an Application that required a Scrollable TextBox. Unfortunately the textbox that is available via the default WP7 controls is not scrollable. Naturally, i was looking for alternative controls/workarounds. But this time Googling did not work. There wasn't any decent work around available. I was about to quit doing the application, but thanks to a friend of mine i didn't. He found of a work around for this :) (had the eureka feeling :P ). OK enough story, lets get down to business.

Solution: 

Key thing: Set the height of the texbox to Auto, attach a scrollviewer to it & enclose it inside a grid.

By scrollable textbox generally, we mean that the container inside the textbox control (that holds the text) should be scrollable. Instead of that, what we are going to do is set the height of the textbox to "Auto" and put it inside a stackpanel and attach a scrollviewer to this textbox. The idea here is that, instead of moving the container that holds the text, we are moving the entire textbox. Since the height is set to auto, the textbox height extends automatically. To give the user an effect thats is similar to scrolling textbox, it should be enclosed inside a grid. The grid's dimensions should match that of the required textbox.

Code:

<Grid Height="390" HorizontalAlignment="Left" Margin="140,42,0,0" x:Name="grid1" VerticalAlignment="Top" Width="478"  >
            <ScrollViewer VerticalScrollBarVisibility="Auto" >
                <StackPanel Width="469">
                <TextBox AcceptsReturn="True" x:Name="ScrollableTextBox" Height="Auto" MinHeight="320" Width="454" TextWrapping="Wrap"/>
                </StackPanel>
            </ScrollViewer>

            </Grid>

 
Catch:

The catch in this solution is that, as the user keeps typing in and the textbox is just about to extend beyond the region of visibility, the textbox doesn't automatically scroll. The user has to use the scroll gesture and manually pull it up. An alternative is to (Though i haven't tried this) use the Height changed event of the textbox and when it crosses the threshold, programatically scroll up.This would give the feel of a proper Scrollable Textbox.

Hope this solution helped :) 


1 comments:

Post a Comment