So this weekend my project of choice was to build a dial control. I'll post more on that later. But one cool thing I ended up doing was building a custom event on the dial control called OnPosition Changed. Typically when you use or build controls the events you use are more straight forward but this case, we have a dial so the 'mouseover' or click isn't really want you want. So what we want is when the dial moves to a position we want the 'position changed' event called.
To start with you need some custom event args as we want to pass the 'angle' of the dial to the event handler in the consuming application. So the custom event args looks like this:
public class DialEventArgs : EventArgs
{
private double angle;
public DialEventArgs(double _Angle)
{
this.angle = _Angle;
}
public double Angle
{
get
{
return angle;
}
}
}
In this case its a pretty straight forward class that drives from eventargs and we add a constructor that lets us set the angle property easily. Next we need in our control class to define the event like this:
public delegate void PositionChangeHandler (Object Sender, DialEventArgs e);
public event PositionChangeHandler PositionChangedEvent;
protected virtual void OnPositionChanged(DialEventArgs e)
{
PositionChangedEvent(this, e);
}
With this in place a consuming xaml page if they use the control will be able to set an event handler for this event. But first we need to actually call the event when the angle of the dial changes: In the method that sets the angle we have this code:
OnPositionChanged(new DialEventArgs(AngleOfRotation));
Now when you have an event handler set in xaml you get the event called at the correct time. In xaml this might look like this:
<cc:Dial x:Name="NewKnobControl" Height="100" Width="100" PositionChangedEvent="NewKnobControl_PositionChangedEvent" Minimum="45.0" Max="135" >
<cc:Dial.KnobFace>
<Grid >
<Ellipse Fill="Aquamarine" />
<Rectangle x:Name="Indicator" Height="10" Width="49" Fill="Blue" Margin="1,45,50,45" />
</Grid>
</cc:Dial.KnobFace>
</cc:Dial>
Now in the client code you need an event handler and in this case in my demo app it looks like this:
private void NewKnobControl_PositionChangedEvent(Object sender, DialEventArgs e)
{
// applicable values
double Angle = e.Angle;
}
This blog has moved…
14 years ago
i am a c# programer, i am studying the silverlight now.... this is good article!
ReplyDelete