本文主要介绍如何在C1Chart for WPF中创建一个可以移动的线,使得当鼠标拖拽的时候,可以在Chart上自由移动。

为了显示拖拽的线,需要创建一个Marker,本文创建一条竖直的Marker,通过创建ChartPanelObject实现,将ChartPanelObject的Action属性设置为LeftButtonDrag,实现鼠标左键的拖拽。

使用ChartPanelObject创建竖直的线,代码参考:

ChartPanelObject CreateMarker(bool isHorizontal)
        {
            var obj = new ChartPanelObject();
            var bdr = new Border()
            {
                BorderBrush = Background = new SolidColorBrush(Color.FromArgb(150, 255, 2, 2)),
                Padding = new Thickness(2),
            };
            var tb = new TextBlock();
            var bind = new Binding();
            bind.Source = obj;

            if (isHorizontal)
            {
                bdr.BorderThickness = new Thickness(0, 4, 0, 0);
                bdr.Margin = new Thickness(0, -1, 0, 0);
                obj.HorizontalContentAlignment = HorizontalAlignment.Stretch;
                bind.StringFormat = "y={0:#.#}";
                bind.Path = new PropertyPath("DataPoint.Y");
                obj.DataPoint = new Point(double.NaN, 0.5);
            }
            else
            {
                bdr.BorderThickness = new Thickness(4, 0, 0, 0);
                bdr.Margin = new Thickness(-1, 0, 0, 0);
                obj.VerticalContentAlignment = VerticalAlignment.Stretch;
                bind.StringFormat = "x={0:#.#}";
                bind.Path = new PropertyPath("DataPoint.X");
                obj.DataPoint = new Point(2, double.NaN);
            }

            tb.SetBinding(TextBlock.TextProperty, bind);
            bdr.Child = tb;

            bdr.IsHitTestVisible = true;

            obj.Content = bdr;

            return obj;
        }

通过bind.Path = new PropertyPath("DataPoint.X"),让这条拖拽的线展示X轴的数据。

 实现鼠标左键的代码参考:

var vmarker = CreateMarker(false);
            pnl.Children.Add(vmarker);
            vmarker.Action = ChartPanelAction.LeftMouseButtonDrag;

            chart.View.Layers.Add(pnl);

 

 实现的效果如下:

 

 

本文的源代码,请下载:

AddDragLineToChart.zip (340.56 kb)


更多资源

C1Chart的在线英文产品文档地址: 

http://helpcentral.componentone.com/nethelp/c1wpfchart/#!Documents/componentonechartforwpf.htm

 

如果你对C1Chart感兴趣,请到我们的官网下载最新版本:/developer/componentone-winform/controls/chart

如果你有疑问,可以到GCDN论坛获得技术支持:http://gcdn.grapecity.com.cn/showforum-68.html