Skip to main content Skip to footer

Draggable Pointer in C1LinearGauge

C1Gauge (SL and WPF) provides pointers to display values in a range. You may want to change the value by dragging the pointer to a specified value, just like a simple slider control behaves. Handling the relevant mouse events and changing the value based on mouse coordinates is the way to go. Now, the most important part is how detect the value based on mouse coordinates. Unfortunately, there is no inbuilt method which gives you the value from the point, so that has to be calculated manually. The magic formula to get value from a point is below:-

 var pathlength = linearGauge.ActualWidth * linearGauge.XAxisLength;  
 var startposition = linearGauge.ActualWidth * linearGauge.XAxisLocation;  
 var offset = Convert.ToDouble((linearGauge.Maximum - linearGauge.Minimum) / pathlength);  
 var pixelvalue = Convert.ToDouble(offset * startposition);  
 linearGauge.Value = Convert.ToDouble((e.GetPosition(linearGauge).X * offset) - pixelvalue + linearGauge.Minimum);

Lets see how this formula is used with mouse events on C1LinearGauge to change the value:-

linearGauge.MouseLeftButtonDown += (s, e) =>  
 {  
    bdr = e.OriginalSource as Border;  //global varaible  
    isMouseCaptured = true;  
    bdr.Cursor = Cursors.Hand;  
    bdr.CaptureMouse();  
 };  

 linearGauge.MouseMove += (s, e) =>  
 {  
    if (isMouseCaptured)  
    {  
       var pathlength = linearGauge.ActualWidth * linearGauge.XAxisLength;  
       var startposition = linearGauge.ActualWidth * linearGauge.XAxisLocation;  
       var offset = Convert.ToDouble((linearGauge.Maximum - linearGauge.Minimum) / pathlength);  
       var pixelvalue = Convert.ToDouble(offset * startposition);  
       linearGauge.Value = Convert.ToDouble((e.GetPosition(linearGauge).X * offset) - pixelvalue + linearGauge.Minimum);  
       if (linearGauge.Value < linearGauge.Minimum)  
          linearGauge.Value = linearGauge.Minimum;  
       else if (linearGauge.Value > linearGauge.Maximum)  
          linearGauge.Value = linearGauge.Maximum;  
    }  
 };  

 linearGauge.MouseLeftButtonUp += (s, e) =>  
 {  
    if (bdr != null)  
    {  
       bdr.ReleaseMouseCapture();  
       bdr.Cursor = Cursors.Arrow;  
       isMouseCaptured = false;  
    }  
 };

Download Sample

MESCIUS inc.

comments powered by Disqus