我将ObservablePoint添加到笛卡尔图中。我需要在一个窗口中得到这个点的x和y坐标。
我如何使用代码来做到这一点?
我试图将CartesianChart引入UIElement类型,以获取其中的图形元素,但我失败了。
这是我使用的代码:
类
using System.Windows;
using LiveCharts;
using LiveCharts.Wpf;
using LiveCharts.Defaults;
using System.Windows.Media;
using System.Threading.Tasks;
using System;
using System.Threading;
namespace TestChartApp
{
public partial class MainWindow : Window
{
SeriesCollection series = new SeriesCollection();
ChartValues<ObservableValue> observableValues = new ChartValues<ObservableValue>();
LineSeries lineSeries = new LineSeries
{
Stroke = Brushes.Blue,
Fill = Brushes.Transparent,
};
public MainWindow()
{
InitializeComponent();
observableValues.Add(new ObservableValue(0));
lineSeries.Values = observableValues;
series.Add(lineSeries);
myChart.Series = series;
myChart.DataTooltip = null;
myChart.Hoverable = false;
}
}
}
XAML
<Window x:Class="TestChartApp.MainWindow"
...
Title="MainWindow" Height="600" Width="1200" WindowStartupLocation="CenterScreen">
<Grid>
<lvc:CartesianChart x:Name="myChart" DisableAnimations="True" Width="800" HorizontalAlignment="Left">
<lvc:CartesianChart.AxisX>
<lvc:Axis MaxValue="100" MinValue="0" Labels="" Unit="1">
<lvc:Axis.Separator>
<lvc:Separator Step="20">
<lvc:Separator.Stroke>
<SolidColorBrush Color="Gray" />
</lvc:Separator.Stroke>
</lvc:Separator>
</lvc:Axis.Separator>
</lvc:Axis>
</lvc:CartesianChart.AxisX>
<lvc:CartesianChart.AxisY>
<lvc:Axis MaxValue="100" MinValue="-100" Labels="">
<lvc:Axis.Separator>
<lvc:Separator>
<lvc:Separator.Stroke>
<SolidColorBrush Color="Gray" />
</lvc:Separator.Stroke>
</lvc:Separator>
</lvc:Axis.Separator>
</lvc:Axis>
</lvc:CartesianChart.AxisY>
</lvc:CartesianChart>
</Grid>
</Window>
当您可以访问图表时,从映射到SeriesColection.ChartPoints
的SeriesCollection.Values
中找到感兴趣的图表点(例如,按索引映射(:
主窗口.xaml
<Window>
<CartesianChart x:Name="MyChart" />
</Window>
主窗口.xaml.cs
// Get the target series
var firstLineSeries = this.MyChart.Series[0] as LineSeries;
// Get a point from this series (in this case the first)
ChartPoint firstPointInLineSeries = firstLineSeries.ChartPointsElementAt(0);
// Convert the CahrtPoint to common WPF Point
Point convertedChartPoint = firstPointInLineSeries.AsPoint();
// Get the position of this point relative to the chart
Point chartPointPositionInChart = this.MyChart.ConvertToPixels(convertedChartPoint);
// Convert the chart point pixel coordinates
// to the parent Window coordinates
Point chartPointPositionInWindow = this.MyChart.TransformToVisual(this).Transform(chartPointPositionInChart);
您是否尝试过他们文档中的解决方案?链接
private void ChartOnDataClick(object sender, ChartPoint p)
{
var asPixels = cartesianChart1.Base.ConvertToPixels(p.AsPoint());
Console.WriteLine("[EVENT] You clicked (" + p.X + ", " + p.Y + ") in pixels (" +
asPixels.X + ", " + asPixels.Y + ")");
}