by Bobbi Perreault
13. July 2011 21:28
Share on FacebookIn Silverlight 4.0 application I needed to have a line follow the mouse for comparing between line charts. I Googled Silverlight 4.0 custom cursor and number three on the results was my old-old blog post about a custom cursor I put into a drawing program. That took me back a ways. ha ha.
For this app, my needs are simple, heck, I don't even need to hide the cursor. I just want a line to follow the cursor while the mouse is over a specific panel. So here's how I did it.
- I added a Path object to the XAML of my page. This Path needs to be on top, so it's at the bottom of the XAML just before the closing </Grid>. Visibility is turned off so it doean't intrude until needed.
<Path Data="M122,198 L122,583.57233" Fill="#FF01010C" x:Name="cursorline"
Visibility="Collapsed" HorizontalAlignment="Left" Grid.Row="1"
Stretch="Fill" Stroke="Black" UseLayoutRounding="False"
Width="1"/>
- I added mouse move event handlers to the containing grid, called imaginatively LayoutRoot.
<Grid x:Name="LayoutRoot" MouseEnter="LayoutRoot_MouseEnter"
MouseLeave="LayoutRoot_MouseLeave"
MouseMove="LayoutRoot_MouseMove">
- In Mouse Enter event handler, I set the visibility of my path to Visible.
- In Mouse Leave event handler, I set the visibility of my path to Collapsed.
- In Mouse Move event handler, I set the margin of my path to line up with the horizontal position of my cursor. Here's the code.
private void LayoutRoot_MouseEnter(object sender, MouseEventArgs e)
{
cursorline.Visibility = System.Windows.Visibility.Visible;
}
private void LayoutRoot_MouseLeave(object sender, MouseEventArgs e)
{
cursorline.Visibility = System.Windows.Visibility.Collapsed;
}
private void LayoutRoot_MouseMove(object sender, MouseEventArgs e)
{
cursorline.Margin = new Thickness( e.GetPosition(LayoutRoot).X, 0, 0, 0);
Ok then. Have a great day.
