Silverlight Tip of the Day #28: How to Implement a Custom Mouse Cursor
In Tip of the Day #27 we talked about how to change the mouse cursor. But what if you want to have a cursor icon that is not supported by Silverlight? This tutorial will show you how to do it.
Demo (Silverlight 3 Beta 1 required):
The first thing you will want to do is to hide the mouse cursor at the root level of your Silverlight application. In our Page.xaml, we set the Canvas Mouse to “None”:
MainPage.xaml:
<UserControl x:Class="CustomCursor.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Canvas x:Name="LayoutRoot" Cursor="None" Background="White">
</Canvas>
</UserControl>
Next, create a customer Silverlight user control called CustomCursor. The only thing this control need to contain is a Image control.
Cursor.XAML:
<UserControl x:Class="CustomCursor.CustomCursor"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Image x:Name="MyCursor"></Image>
</UserControl>
In the code behind for the CustomCursor class add a method to set the image and another method to position the control.
Cursor.XAML.cs:
namespace CustomCursor
{
public partial class CustomCursor : UserControl
{
public CustomCursor()
{
InitializeComponent();
}
public void SetCursor(string resource)
{
Uri uri = new Uri(resource, UriKind.Relative);
MyCursor.Source = new System.Windows.Media.Imaging.BitmapImage(uri);
}
public void MoveTo(Point pt)
{
this.SetValue(Canvas.LeftProperty, pt.X);
this.SetValue(Canvas.TopProperty, pt.Y);
}
}
}
Finally, go back to MainPage.xaml.cs and add an instance of your CustomCursor to your Canvas. Also, monitor for the MouseMove event so you can position the cursor to be at the location of your mouse.
namespace CustomCursor
{
public partial class MainPage : UserControl
{
CustomCursor customCursor = new CustomCursor();
public MainPage()
{
InitializeComponent();
customCursor.SetCursor("fireball.png");
LayoutRoot.Children.Add(customCursor);
this.MouseMove += new MouseEventHandler(MainPage_MouseMove);
}
void MainPage_MouseMove(object sender, MouseEventArgs e)
{
customCursor.MoveTo(e.GetPosition(null));
}
}
}
Thank you,
--Mike Snow
Subscribe in a reader