private void AddChart() { cs = new ChartStyleGridlines(); cs.ChartCanvas = chartCanvas; cs.TextCanvas = textCanvas; cs.Title = "Sine and Cosine Chart"; cs.Xmin = 0; cs.Xmax = 7; cs.Ymin = -1.5; cs.Ymax = 1.5; cs.YTick = 0.5; cs.GridlinePattern = ChartStyleGridlines.GridlinePatternEnum.Dot; cs.GridlineColor = new SolidColorBrush(Colors.Black); cs.AddChartStyle(tbTitle); ds.LineColor = new SolidColorBrush(Colors.Blue); ds.LineThickness = 1; ds.SeriesName = "Sine"; for (int i = 0; i < 36; i++) { double x = i / 5.0; double y = Math.Sin(x); ds.LineSeries.Points.Add(new Point(x, y)); } dc.DataList.Add(ds); ds = new DataSeries(); ds.LineColor = new SolidColorBrush(Colors.Red); ds.SeriesName = "Cosine"; ds.LinePattern = DataSeries.LinePatternEnum.DashDot; ds.LineThickness = 2; for (int i = 0; i < 36; i++) { double x = i / 5.0; double y = Math.Cos(x); ds.LineSeries.Points.Add(new Point(x, y)); } dc.DataList.Add(ds); ds = new DataSeries(); ds.LineColor = new SolidColorBrush(Colors.Green); ds.SeriesName = "Sine^2"; ds.LinePattern = DataSeries.LinePatternEnum.Dot; ds.LineThickness = 2; for (int i = 0; i < 36; i++) { double x = i / 5.0; double y = Math.Sin(x) * Math.Sin(x); ds.LineSeries.Points.Add(new Point(x, y)); } dc.DataList.Add(ds); dc.AddLines(chartCanvas, cs); lg.LegendCanvas = legendCanvas; lg.IsLegend = true; lg.IsBorder = true; lg.AddLegend(cs, dc); }
public void AddLegend(ChartStyleGridlines cs, DataCollection dc) { TextBlock tb = new TextBlock(); if (dc.DataList.Count < 1 || !IsLegend) { return; } int n = 0; string[] legendLabels = new string[dc.DataList.Count]; foreach (DataSeries ds in dc.DataList) { legendLabels[n] = ds.SeriesName; n++; } double legendWidth = 0; Size size = new Size(0, 0); for (int i = 0; i < legendLabels.Length; i++) { tb = new TextBlock(); tb.Text = legendLabels[i]; tb.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity)); size = tb.DesiredSize; if (legendWidth < size.Width) { legendWidth = size.Width; } } legendWidth += 80; legendCanvas.Width = legendWidth + 5; double legendHeight = 30 * dc.DataList.Count; double sx = 6; double sy = 15; double textHeight = size.Height; double lineLength = 34; Rectangle legendRect = new Rectangle(); legendRect.Stroke = new SolidColorBrush(Colors.Black); legendRect.Width = legendWidth; legendRect.Height = legendHeight; if (IsLegend && IsBorder) { LegendCanvas.Children.Add(legendRect); } n = 1; foreach (DataSeries ds in dc.DataList) { double xSymbol = sx + lineLength / 2; double xText = 2 * sx + lineLength; double yText = n * sy + (2 * n - 1) * textHeight / 2; Line line = new Line(); AddLinePattern(line, ds); line.X1 = sx; line.Y1 = yText; line.X2 = sx + lineLength; line.Y2 = yText; LegendCanvas.Children.Add(line); tb = new TextBlock(); tb.FontSize = 15; tb.Text = ds.SeriesName; LegendCanvas.Children.Add(tb); Canvas.SetTop(tb, yText - 15); Canvas.SetLeft(tb, xText + 10); n++; } }