Silverlight 4 Rough Notes: Mousewheel Support in Controls

Note – these posts are put together after a short time with Silverlight 4 as a way of providing pointers to some of the new features that Silverlight 4 has to offer. I’m posting these from the PDC as Silverlight 4 is announced for the first time so please bear that in mind when working through these posts.

Silverlight 3 added support for the MouseWheel event and it is present on the UIElement class. However, the controls in Silverlight don’t generally respond well to mouse wheel events whereas in Silverlight 4 you should expect to see controls doing the right thing in response to the mousewheel.

As an example, here’s a quick ListBox;

<UserControl x:Class="SilverlightApplication30.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:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">
        <ListBox
            ItemsSource="{Binding}" />
    </Grid>
</UserControl>

with a little code-behind to add some items to that ListBox;

  public partial class MainPage : UserControl
  {
    public MainPage()
    {
      InitializeComponent();

      this.Loaded += (s, e) =>
        {
          this.DataContext = from i in Enumerable.Range(1, 200)
                             select string.Format("Item {0}", i);
        };
    }
  }

and my ListBox pops up;

image

and immediately does the right thing with respect to mouse wheel scrolling 🙂