C1Gauge(Silverligth和WPF)通过一个指针来显示一个范围内的值,在某些场景我们希望通过拖动指针来修改C1Gauge的值,从而实现类型Silder控件的功能。
我们可以通过鼠标事件,并根据鼠标所在的位置来改变C1Gauge的值。现在最关键的一步就是得到鼠标的位置。遗憾的是C1Gauge并没有内置的方法来返回鼠标的位置,只能自己计算得到,下面的代码就演示了通过位置计算出相应的值:
 
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);
复制代码
下面代码演示了如何在鼠标事件中来动态计算该值:
 
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;
    }
};
复制代码
附上源码:
VS2010 + C1Gauge for WPF 2011V3(适用于C1Gauge for Silverlight 2011V3)
[attach]2138[/attach]
 
GaugeDragDrop.zip (13.99 K, 下载次数:15)

zip(2012-3-12 9:30:46 上传)