MouseWheel Behavior for Silverlight
Earlier today I saw a comment about adding mouse wheel support for Silverlight apps and controls in the form of a behavior. I thought I’d put together a sample of a using the MouseWheelScroll behavior that already exists in Silverlight.FX. Its really quite straightforward… just attach one to any ScrollViewer control (actually any control that provides the scrolling automation peer functionality), or to some control that contains one in its control template (for example, a TextBox).
On the right is a screenshot of the live sample (note that this does work with Silverlight 2 as well). You can download the sample, and you can also download Silverlight.FX from its project page along with associated samples to see what else is in the works.
Here are the relevant bits of XAML:
<UserControl ... xmlns:fxui="clr-namespace:SilverlightFX.UserInterface;assembly=SilverlightFX"> <Grid> <ScrollViewer VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Disabled"> <fxui:Interaction.Behaviors> <fxui:MouseWheelScroll /> </fxui:Interaction.Behaviors> <Image Source="/SL3Poster.png" Width="450" /> </ScrollViewer> <TextBox VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Disabled" TextWrapping="Wrap"> <fxui:Interaction.Behaviors> <fxui:MouseWheelScroll /> </fxui:Interaction.Behaviors> <TextBox.Text>Lorem ipsum dolor sit amet...</TextBox.Text> </TextBox> </Grid> </UserControl>
Thats pretty much it! You don’t have to write any code, much less deal with browser APIs to handle mouse scroll events! If browser access is turned off, this just degrades gracefully. Regular scrolling continues to work of course. I really love the behavior concept for the way it enables adding interactivity to your XAML, while keeping it clean, declarative and super-simple.