There has been quite a few blog posts on how to create custom cursors in Silverlight, but I felt some of them were very limited or not very re-useable, or required you to put the cursor in the layout and put restrictions on your layout (like for instance requiring you to use a Canvas as parent for your cursor). So I ended up writing my own class for it that doesn’t have any of these restrictions.
The basic idea is the same as other approaches out there: You “disable” the cursor on your element by setting myElement.Cursor = Cursors.None. Next you move a custom UIElement around on top of your layout which represents your custom cursor. My approach uses a Popup, and therefore never requires you to modify your layout, and you can easily change the cursor on the fly. The cursor look is defined using a DataTemplate and can contain animations and so on.
All you need to do is define a DataTemplate and use the Attached Property to define the template. Below is an example of this working on a border element:
<UserControl x:Class="CustomCursor.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SharpGIS.CustomCursor">
<UserControl.Resources>
<DataTemplate x:Key="CircleCursor">
<Ellipse Fill="Red" Width="20" Height="20" />
</DataTemplate>
</UserControl.Resources>
<Grid>
<Border Background="Blue"
local:CustomCursor.CursorTemplate="{StaticResource CircleCursor}" />
</Grid>
</UserControl>
And that’s all there is to it!
If you need to customize where the centering of the element is, simply apply a TranslateTranform to the element. Ie. if you want the above circle to center on the mouse location, add a TranslateTransform of –10,-10 to the ellipse.
Downloads:
Update: Someone awesome ported this to Windows Store apps as well! Go download here: http://customcursor.codeplex.com/