允许用户通过单击图表在wpf图表上创建一个系列

时间:2011-01-31 15:44:10

标签: wpf charts toolkit

我的WPF图表目前正在显示区域系列。我需要允许用户单击图表并为Line系列添加新点。我遇到的问题是我似乎无法找到将点从MouseButtonEventArgs转换为LineDataPoint的方法。

private void chtPowerFlowMap_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        Point p = e.GetPosition(chtPowerFlowMap);

        points.Add(p); //Issue here is this will return a point in screen coordinates and not in chart coordinates

        ls.ItemsSource = points; //ls is an existing lineseries and points is a List<Point> object

        chtPowerFlowMap.Series.Add(ls);
    }

提前致谢。

1 个答案:

答案 0 :(得分:1)

这是一个完整的解决方案。您可以点击图表上的任意位置,该地点会有一个新点。

<强> 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 });
    }
}
相关问题