We can easily handle the various mouse events by referring their events. These events are usually available as properties of the elements we work with.

The following code sample access those properties using their corresponding attributes in the XAML code.

The XAML file:

<UserControl x:Class="SilverlightApplication13.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
    <Canvas x:Name="Surface" Grid.Column="0">        
        <Ellipse Fill="Blue" Width="80" Height="80" 
                 MouseMove="EllipseMouseMove"
                 MouseEnter="EllipseMouseEnter"
                 MouseLeave="EllipseMouseLeave"
                 MouseWheel="EllipseMouseWheel"     
                 >            
        </Ellipse>        
    </Canvas>

        <TextBox FontSize="20" x:Name="Msg" Grid.Column="1"></TextBox>

    </Grid>
</UserControl>

The code behind in C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightApplication13
{
    public partial class MainPage : UserControl
    {
        private int counter = 0;
        public MainPage()
        {
            InitializeComponent();
        }

        private void EllipseMouseEnter(object sender, MouseEventArgs e)
        {
            Msg.Text += "\n"+ counter + ": EllipseMouseEnter";
            counter++;
        }

        private void EllipseMouseMove(object sender, MouseEventArgs e)
        {
            Msg.Text += "\n"+ counter + ": EllipseMouseMove";
            counter++;
        }

        private void EllipseMouseLeave(object sender, MouseEventArgs e)
        {
            Msg.Text += "\n"+ counter + ": EllipseMouseLeave";
            counter++;
        }

        private void EllipseMouseWheel(object sender, MouseEventArgs e)
        {
            Msg.Text += "\n"+ counter + ": EllipseMouseWheel";
            counter++;
        }
    }
}

The following is a short video clip that shows the execution of this code sample and explains it.

Leave a Reply

Your email address will not be published. Required fields are marked *