Even though this is not a complex process, I thought this will help someone to get started with!
Now why would anyone want to represent the position of Mouse Pointer in their UI Element?
This originated for the requirement of a
Rating Control in WPF, (the star thing, well we have
RadioButtonList
in CodeProject pages!). Visual representation of the mouse co-ordinates makes the function of the control, Sacha Barber in his
article used clipping on of the two stars in the control template. This is an alternate approach for this need. That's enough talk for this tip and here goes the code!
The XAML Designer Code:
<Border Name="border" Background="Yellow" BorderBrush="Green" BorderThickness="3" Width="200" Height="200" SnapsToDevicePixels="True"/>
The Code behind C#:
private bool TrackHorizontally = false;
this.border.MouseMove += new MouseEventHandler(border_MouseMove);
void border_MouseMove(object sender, MouseEventArgs e)
{
var cBegin = Colors.Green;
var cEnd = Colors.Yellow;
GradientStop gs1, gs2;
var brush = new LinearGradientBrush();
var gs0 = new GradientStop(cBegin, 0);
var gs3 = new GradientStop(cEnd, 1.0);
Point p = e.GetPosition(this.border);
var factor = TrackHorizontally ? p.Y / this.border.Height : p.X / this.border.Width;
if (TrackHorizontally)
{
brush.StartPoint = new Point(0.5, 0);
brush.EndPoint = new Point(0.5, 1);
gs1 = new GradientStop(cBegin, factor);
gs2 = new GradientStop(cEnd, factor);
}
else
{
brush.StartPoint = new Point(0, 0.5);
brush.EndPoint = new Point(1, 0.5);
gs1 = new GradientStop(cBegin, factor);
gs2 = new GradientStop(cEnd, factor);
}
brush.GradientStops = new GradientStopCollection { gs0, gs1, gs2, gs3 };
this.border.Background = brush;
}
}
How it works!?
Nothing complex to explain,there are four gradient stops, two gradient stops together makes the start and end point of a Color, and just by adjusting the gradient stops values based on the factor (YCoordinate / Height) we make it appear to track the mouse pointer.
That's it, hope it helps! :)