Allow a user to create a line series on a wpf chart by clicking on the chart

穿精又带淫゛_ 提交于 2019-12-04 19:01:44

Here is a complete solution. You can click anywhere on the chart and there will be a new point at that palce.

MainWindows.xaml

<chart:Chart x:Name="chart" MouseLeftButtonDown="Chart_MouseLeftButtonDown">
        <chart:LineSeries ItemsSource="{Binding}" x:Name="lineSeries"
                          DependentValuePath="Value"
                          IndependentValuePath="Date"/>
</chart:Chart>

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    private ObservableCollection<Item> items;

    public MainWindow()
    {
        InitializeComponent();
        Random rd = new Random();

        items = new ObservableCollection<Item>(
                Enumerable.Range(0, 10)
                .Select(i => new Item
                {
                    Date = DateTime.Now.AddMonths(i - 10),
                    Value = rd.Next(10,50)
                }));
        this.DataContext = items;
    }

    public class Item
    {
        public DateTime Date { get; set; }
        public double Value { get; set; }
    }

    private void Chart_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        var p = Mouse.GetPosition(this.lineSeries);
        //ranges in the real values
        var left = items.Min(i => i.Date);
        var right = items.Max(i => i.Date);
        var top = items.Max(i => i.Value);
        var bottom = items.Min(i => i.Value);

        var hRange = right - left;
        var vRange = top - bottom;

        //ranges in the pixels
        var width = this.lineSeries.ActualWidth;
        var height = this.lineSeries.ActualHeight;

        //from the pixels to the real value
        var currentX = left + TimeSpan.FromTicks((long)(hRange.Ticks * p.X / width));
        var currentY = top - vRange * p.Y / height;

        this.items.Add(new Item { Date = currentX, Value = currentY });
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!