Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2924-dotnet-core/HeuristicLab.Analysis.Views/3.3/IndexedDataTableView.cs @ 15986

Last change on this file since 15986 was 15583, checked in by swagner, 7 years ago

#2640: Updated year of copyrights in license headers

File size: 28.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using HeuristicLab.Collections;
23using HeuristicLab.Core.Views;
24using HeuristicLab.MainForm;
25using System;
26using System.Collections.Generic;
27using System.Drawing;
28using System.Linq;
29using System.Windows.Forms;
30using System.Windows.Forms.DataVisualization.Charting;
31
32namespace HeuristicLab.Analysis.Views {
33  [View("IndexedDataTable View")]
34  [Content(typeof(IndexedDataTable<>), true)]
35  public partial class IndexedDataTableView<T> : NamedItemView {
36    protected List<Series> invisibleSeries;
37    protected Dictionary<IObservableList<Tuple<T, double>>, IndexedDataRow<T>> valuesRowsTable;
38
39    public new IndexedDataTable<T> Content {
40      get { return (IndexedDataTable<T>)base.Content; }
41      set { base.Content = value; }
42    }
43
44    public IndexedDataTableView() {
45      InitializeComponent();
46      valuesRowsTable = new Dictionary<IObservableList<Tuple<T, double>>, IndexedDataRow<T>>();
47      invisibleSeries = new List<Series>();
48      chart.CustomizeAllChartAreas();
49      chart.ChartAreas[0].CursorX.Interval = 1;
50      chart.SuppressExceptions = true;
51    }
52
53    #region Event Handler Registration
54    protected override void DeregisterContentEvents() {
55      foreach (var row in Content.Rows)
56        DeregisterDataRowEvents(row);
57      Content.VisualPropertiesChanged -= new EventHandler(Content_VisualPropertiesChanged);
58      Content.Rows.ItemsAdded -= new CollectionItemsChangedEventHandler<IndexedDataRow<T>>(Rows_ItemsAdded);
59      Content.Rows.ItemsRemoved -= new CollectionItemsChangedEventHandler<IndexedDataRow<T>>(Rows_ItemsRemoved);
60      Content.Rows.ItemsReplaced -= new CollectionItemsChangedEventHandler<IndexedDataRow<T>>(Rows_ItemsReplaced);
61      Content.Rows.CollectionReset -= new CollectionItemsChangedEventHandler<IndexedDataRow<T>>(Rows_CollectionReset);
62      base.DeregisterContentEvents();
63    }
64
65    protected override void RegisterContentEvents() {
66      base.RegisterContentEvents();
67      Content.VisualPropertiesChanged += new EventHandler(Content_VisualPropertiesChanged);
68      Content.Rows.ItemsAdded += new CollectionItemsChangedEventHandler<IndexedDataRow<T>>(Rows_ItemsAdded);
69      Content.Rows.ItemsRemoved += new CollectionItemsChangedEventHandler<IndexedDataRow<T>>(Rows_ItemsRemoved);
70      Content.Rows.ItemsReplaced += new CollectionItemsChangedEventHandler<IndexedDataRow<T>>(Rows_ItemsReplaced);
71      Content.Rows.CollectionReset += new CollectionItemsChangedEventHandler<IndexedDataRow<T>>(Rows_CollectionReset);
72      foreach (var row in Content.Rows)
73        RegisterDataRowEvents(row);
74    }
75
76    /// <summary>
77    /// Automatically called for every existing data row and whenever a data row is added
78    /// to the data table. Do not call this method directly.
79    /// </summary>
80    /// <param name="row">The DataRow that was added.</param>
81    protected virtual void RegisterDataRowEvents(IndexedDataRow<T> row) {
82      row.NameChanged += new EventHandler(Row_NameChanged);
83      row.VisualPropertiesChanged += new EventHandler(Row_VisualPropertiesChanged);
84      valuesRowsTable.Add(row.Values, row);
85      row.Values.ItemsAdded += new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_ItemsAdded);
86      row.Values.ItemsRemoved += new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_ItemsRemoved);
87      row.Values.ItemsReplaced += new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_ItemsReplaced);
88      row.Values.ItemsMoved += new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_ItemsMoved);
89      row.Values.CollectionReset += new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_CollectionReset);
90    }
91
92    /// <summary>
93    /// Automatically called for every data row that is removed from the DataTable. Do
94    /// not directly call this method.
95    /// </summary>
96    /// <param name="row">The DataRow that was removed.</param>
97    protected virtual void DeregisterDataRowEvents(IndexedDataRow<T> row) {
98      row.Values.ItemsAdded -= new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_ItemsAdded);
99      row.Values.ItemsRemoved -= new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_ItemsRemoved);
100      row.Values.ItemsReplaced -= new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_ItemsReplaced);
101      row.Values.ItemsMoved -= new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_ItemsMoved);
102      row.Values.CollectionReset -= new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_CollectionReset);
103      valuesRowsTable.Remove(row.Values);
104      row.VisualPropertiesChanged -= new EventHandler(Row_VisualPropertiesChanged);
105      row.NameChanged -= new EventHandler(Row_NameChanged);
106    }
107    #endregion
108
109    protected override void OnContentChanged() {
110      base.OnContentChanged();
111      invisibleSeries.Clear();
112      chart.Titles[0].Text = string.Empty;
113      chart.ChartAreas[0].AxisX.Title = string.Empty;
114      chart.ChartAreas[0].AxisY.Title = string.Empty;
115      chart.ChartAreas[0].AxisY2.Title = string.Empty;
116      chart.ChartAreas[0].AxisX.IsLogarithmic = false;
117      chart.ChartAreas[0].AxisX2.IsLogarithmic = false;
118      chart.ChartAreas[0].AxisY.IsLogarithmic = false;
119      chart.ChartAreas[0].AxisY2.IsLogarithmic = false;
120      chart.Series.Clear();
121      if (Content != null) {
122        chart.Titles[0].Text = Content.Name;
123        foreach (var row in Content.Rows)
124          AddDataRow(row);
125        ConfigureChartArea(chart.ChartAreas[0]);
126        RecalculateAxesScale(chart.ChartAreas[0]);
127      }
128    }
129
130    protected override void SetEnabledStateOfControls() {
131      base.SetEnabledStateOfControls();
132      chart.Enabled = Content != null;
133    }
134
135    /// <summary>
136    /// Add the DataRow as a series to the chart.
137    /// </summary>
138    /// <param name="row">DataRow to add as series to the chart.</param>
139    protected virtual void AddDataRow(IndexedDataRow<T> row) {
140      if (row.Values.Count == 0) return;
141
142      Series series = new Series(row.Name);
143      if (row.VisualProperties.DisplayName.Trim() != String.Empty) series.LegendText = row.VisualProperties.DisplayName;
144      else series.LegendText = row.Name;
145      ConfigureSeries(series, row);
146      FillSeriesWithRowValues(series, row);
147
148      chart.Series.Add(series);
149      ConfigureChartArea(chart.ChartAreas[0]);
150      RecalculateAxesScale(chart.ChartAreas[0]);
151      UpdateYCursorInterval();
152    }
153
154    private void ConfigureSeries(Series series, IndexedDataRow<T> row) {
155      RemoveCustomPropertyIfExists(series, "PointWidth");
156      series.BorderWidth = 1;
157      series.BorderDashStyle = ChartDashStyle.Solid;
158      series.BorderColor = Color.Empty;
159
160      series.Color = row.VisualProperties.Color;
161      series.IsVisibleInLegend = row.VisualProperties.IsVisibleInLegend;
162
163      series.SmartLabelStyle.Enabled = true;
164      series.SmartLabelStyle.AllowOutsidePlotArea = LabelOutsidePlotAreaStyle.No;
165      series.SmartLabelStyle.CalloutLineAnchorCapStyle = LineAnchorCapStyle.None;
166      series.SmartLabelStyle.CalloutLineColor = series.Color;
167      series.SmartLabelStyle.CalloutLineWidth = 2;
168      series.SmartLabelStyle.CalloutStyle = LabelCalloutStyle.Underlined;
169      series.SmartLabelStyle.IsOverlappedHidden = false;
170      series.SmartLabelStyle.MaxMovingDistance = 200;
171
172      switch (row.VisualProperties.ChartType) {
173        case DataRowVisualProperties.DataRowChartType.Line:
174          series.ChartType = SeriesChartType.FastLine;
175          series.BorderWidth = row.VisualProperties.LineWidth;
176          series.BorderDashStyle = ConvertLineStyle(row.VisualProperties.LineStyle);
177          break;
178        case DataRowVisualProperties.DataRowChartType.Bars:
179          // Bar is incompatible with anything but Bar and StackedBar*
180          if (!chart.Series.Any(x => x.ChartType != SeriesChartType.Bar && x.ChartType != SeriesChartType.StackedBar && x.ChartType != SeriesChartType.StackedBar100)) {
181            series.ChartType = SeriesChartType.Bar;
182            chart.ChartAreas[0].AxisX.Interval = 1;
183          } else {
184            series.ChartType = SeriesChartType.FastPoint; //default
185            row.VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points;
186          }
187          break;
188        case DataRowVisualProperties.DataRowChartType.Columns:
189          series.ChartType = SeriesChartType.Column;
190          break;
191        case DataRowVisualProperties.DataRowChartType.Points:
192          series.ChartType = SeriesChartType.FastPoint;
193          break;
194        case DataRowVisualProperties.DataRowChartType.StepLine:
195          series.ChartType = SeriesChartType.StepLine;
196          series.BorderWidth = row.VisualProperties.LineWidth;
197          series.BorderDashStyle = ConvertLineStyle(row.VisualProperties.LineStyle);
198          break;
199        default:
200          series.ChartType = SeriesChartType.FastPoint;
201          break;
202      }
203      series.YAxisType = row.VisualProperties.SecondYAxis ? AxisType.Secondary : AxisType.Primary;
204      series.XAxisType = row.VisualProperties.SecondXAxis ? AxisType.Secondary : AxisType.Primary;
205      if (row.VisualProperties.DisplayName.Trim() != String.Empty) series.LegendText = row.VisualProperties.DisplayName;
206      else series.LegendText = row.Name;
207      series.ToolTip = series.LegendText + " X = #VALX, Y = #VALY";
208    }
209
210    private void ConfigureChartArea(ChartArea area) {
211      if (Content.VisualProperties.TitleFont != null) chart.Titles[0].Font = Content.VisualProperties.TitleFont;
212      if (!Content.VisualProperties.TitleColor.IsEmpty) chart.Titles[0].ForeColor = Content.VisualProperties.TitleColor;
213
214      if (Content.VisualProperties.AxisTitleFont != null) area.AxisX.TitleFont = Content.VisualProperties.AxisTitleFont;
215      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisX.TitleForeColor = Content.VisualProperties.AxisTitleColor;
216      area.AxisX.Title = Content.VisualProperties.XAxisTitle;
217
218      if (Content.VisualProperties.AxisTitleFont != null) area.AxisX2.TitleFont = Content.VisualProperties.AxisTitleFont;
219      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisX2.TitleForeColor = Content.VisualProperties.AxisTitleColor;
220      area.AxisX2.Title = Content.VisualProperties.SecondXAxisTitle;
221
222      if (Content.VisualProperties.AxisTitleFont != null) area.AxisY.TitleFont = Content.VisualProperties.AxisTitleFont;
223      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisY.TitleForeColor = Content.VisualProperties.AxisTitleColor;
224      area.AxisY.Title = Content.VisualProperties.YAxisTitle;
225
226      if (Content.VisualProperties.AxisTitleFont != null) area.AxisY2.TitleFont = Content.VisualProperties.AxisTitleFont;
227      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisY2.TitleForeColor = Content.VisualProperties.AxisTitleColor;
228      area.AxisY2.Title = Content.VisualProperties.SecondYAxisTitle;
229
230      if (typeof(T).Equals(typeof(DateTime))) {
231        area.AxisX.IntervalType = DateTimeIntervalType.Hours;
232        area.AxisX.LabelStyle.Format = "dd.MM.yyyy HH:mm";
233        area.AxisX.IntervalAutoMode = IntervalAutoMode.VariableCount;
234      }
235    }
236
237    private void RecalculateAxesScale(ChartArea area) {
238      // Reset the axes bounds so that RecalculateAxesScale() will assign new bounds
239      foreach (Axis a in area.Axes) {
240        a.Minimum = double.NaN;
241        a.Maximum = double.NaN;
242      }
243
244      if (chart.Series.Any(x => x.Enabled && x.XAxisType == AxisType.Primary && (x.Points.Count == 0 || x.Points.Any(y => y.XValue <= 0))))
245        area.AxisX.IsLogarithmic = false;
246      else area.AxisX.IsLogarithmic = Content.VisualProperties.XAxisLogScale;
247      if (chart.Series.Any(x => x.Enabled && x.XAxisType == AxisType.Secondary && (x.Points.Count == 0 || x.Points.Any(y => y.XValue <= 0))))
248        area.AxisX2.IsLogarithmic = false;
249      else area.AxisX2.IsLogarithmic = Content.VisualProperties.SecondXAxisLogScale;
250
251      if (chart.Series.Any(x => x.Enabled && x.YAxisType == AxisType.Primary && (x.Points.Count == 0 || x.Points.Any(y => y.YValues.Min() <= 0))))
252        area.AxisY.IsLogarithmic = false;
253      else area.AxisY.IsLogarithmic = Content.VisualProperties.YAxisLogScale;
254      if (chart.Series.Any(x => x.Enabled && x.YAxisType == AxisType.Secondary && (x.Points.Count == 0 || x.Points.Any(y => y.YValues.Min() <= 0))))
255        area.AxisY2.IsLogarithmic = false;
256      else area.AxisY2.IsLogarithmic = Content.VisualProperties.SecondYAxisLogScale;
257
258      area.RecalculateAxesScale();
259      area.AxisX.IsMarginVisible = false;
260      area.AxisX2.IsMarginVisible = false;
261
262      area.AxisX.IsStartedFromZero = Content.Rows.Where(x => !x.VisualProperties.SecondXAxis).Any(x => x.VisualProperties.StartIndexZero);
263      area.AxisX2.IsStartedFromZero = Content.Rows.Where(x => x.VisualProperties.SecondXAxis).Any(x => x.VisualProperties.StartIndexZero);
264
265      if (!Content.VisualProperties.XAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.XAxisMinimumFixedValue)) area.AxisX.Minimum = Content.VisualProperties.XAxisMinimumFixedValue;
266      if (!Content.VisualProperties.XAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.XAxisMaximumFixedValue)) area.AxisX.Maximum = Content.VisualProperties.XAxisMaximumFixedValue;
267      if (!Content.VisualProperties.SecondXAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.SecondXAxisMinimumFixedValue)) area.AxisX2.Minimum = Content.VisualProperties.SecondXAxisMinimumFixedValue;
268      if (!Content.VisualProperties.SecondXAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.SecondXAxisMaximumFixedValue)) area.AxisX2.Maximum = Content.VisualProperties.SecondXAxisMaximumFixedValue;
269      if (!Content.VisualProperties.YAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.YAxisMinimumFixedValue)) area.AxisY.Minimum = Content.VisualProperties.YAxisMinimumFixedValue;
270      if (!Content.VisualProperties.YAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.YAxisMaximumFixedValue)) area.AxisY.Maximum = Content.VisualProperties.YAxisMaximumFixedValue;
271      if (!Content.VisualProperties.SecondYAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.SecondYAxisMinimumFixedValue)) area.AxisY2.Minimum = Content.VisualProperties.SecondYAxisMinimumFixedValue;
272      if (!Content.VisualProperties.SecondYAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.SecondYAxisMaximumFixedValue)) area.AxisY2.Maximum = Content.VisualProperties.SecondYAxisMaximumFixedValue;
273      if (area.AxisX.Minimum >= area.AxisX.Maximum) area.AxisX.Maximum = area.AxisX.Minimum + 1;
274      if (area.AxisX2.Minimum >= area.AxisX2.Maximum) area.AxisX2.Maximum = area.AxisX2.Minimum + 1;
275      if (area.AxisY.Minimum >= area.AxisY.Maximum) area.AxisY.Maximum = area.AxisY.Minimum + 1;
276      if (area.AxisY2.Minimum >= area.AxisY2.Maximum) area.AxisY2.Maximum = area.AxisY2.Minimum + 1;
277    }
278
279    /// <summary>
280    /// Set the Y Cursor interval to visible points of enabled series.
281    /// </summary>
282    protected virtual void UpdateYCursorInterval() {
283      double interestingValuesRange = (
284        from series in chart.Series
285        where series.Enabled
286        let values = (from point in series.Points
287                      where !point.IsEmpty
288                      select point.YValues[0]).DefaultIfEmpty(1.0)
289        let range = values.Max() - values.Min()
290        where range > 0.0
291        select range
292        ).DefaultIfEmpty(1.0).Min();
293
294      double digits = (int)Math.Log10(interestingValuesRange) - 3;
295      double yZoomInterval = Math.Pow(10, digits);
296      this.chart.ChartAreas[0].CursorY.Interval = yZoomInterval;
297    }
298
299
300    /// <summary>
301    /// Remove the corresponding series for a certain DataRow.
302    /// </summary>
303    /// <param name="row">DataRow which series should be removed.</param>
304    protected virtual void RemoveDataRow(IndexedDataRow<T> row) {
305      if (chart.Series.All(x => x.Name != row.Name)) return;
306      Series series = chart.Series[row.Name];
307      chart.Series.Remove(series);
308      if (invisibleSeries.Contains(series))
309        invisibleSeries.Remove(series);
310      RecalculateAxesScale(chart.ChartAreas[0]);
311    }
312
313    #region Event Handlers
314    #region Content Event Handlers
315    protected override void Content_NameChanged(object sender, EventArgs e) {
316      if (InvokeRequired)
317        Invoke(new EventHandler(Content_NameChanged), sender, e);
318      else {
319        chart.Titles[0].Text = Content.Name;
320        base.Content_NameChanged(sender, e);
321      }
322    }
323    private void Content_VisualPropertiesChanged(object sender, EventArgs e) {
324      if (InvokeRequired)
325        Invoke(new EventHandler(Content_VisualPropertiesChanged), sender, e);
326      else {
327        ConfigureChartArea(chart.ChartAreas[0]);
328        RecalculateAxesScale(chart.ChartAreas[0]); // axes min/max could have changed
329      }
330    }
331    #endregion
332    #region Rows Event Handlers
333    private void Rows_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedDataRow<T>> e) {
334      if (InvokeRequired)
335        Invoke(new CollectionItemsChangedEventHandler<IndexedDataRow<T>>(Rows_ItemsAdded), sender, e);
336      else {
337        foreach (var row in e.Items) {
338          AddDataRow(row);
339          RegisterDataRowEvents(row);
340        }
341      }
342    }
343    private void Rows_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IndexedDataRow<T>> e) {
344      if (InvokeRequired)
345        Invoke(new CollectionItemsChangedEventHandler<IndexedDataRow<T>>(Rows_ItemsRemoved), sender, e);
346      else {
347        foreach (var row in e.Items) {
348          DeregisterDataRowEvents(row);
349          RemoveDataRow(row);
350        }
351      }
352    }
353    private void Rows_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<IndexedDataRow<T>> e) {
354      if (InvokeRequired)
355        Invoke(new CollectionItemsChangedEventHandler<IndexedDataRow<T>>(Rows_ItemsReplaced), sender, e);
356      else {
357        foreach (var row in e.OldItems) {
358          DeregisterDataRowEvents(row);
359          RemoveDataRow(row);
360        }
361        foreach (var row in e.Items) {
362          AddDataRow(row);
363          RegisterDataRowEvents(row);
364        }
365      }
366    }
367    private void Rows_CollectionReset(object sender, CollectionItemsChangedEventArgs<IndexedDataRow<T>> e) {
368      if (InvokeRequired)
369        Invoke(new CollectionItemsChangedEventHandler<IndexedDataRow<T>>(Rows_CollectionReset), sender, e);
370      else {
371        foreach (var row in e.OldItems) {
372          DeregisterDataRowEvents(row);
373          RemoveDataRow(row);
374        }
375        foreach (var row in e.Items) {
376          AddDataRow(row);
377          RegisterDataRowEvents(row);
378        }
379      }
380    }
381    #endregion
382    #region Row Event Handlers
383    private void Row_VisualPropertiesChanged(object sender, EventArgs e) {
384      if (InvokeRequired)
385        Invoke(new EventHandler(Row_VisualPropertiesChanged), sender, e);
386      else {
387        var row = (IndexedDataRow<T>)sender;
388        Series series = chart.Series[row.Name];
389        series.Points.Clear();
390        ConfigureSeries(series, row);
391        FillSeriesWithRowValues(series, row);
392        RecalculateAxesScale(chart.ChartAreas[0]);
393      }
394    }
395    private void Row_NameChanged(object sender, EventArgs e) {
396      if (InvokeRequired)
397        Invoke(new EventHandler(Row_NameChanged), sender, e);
398      else {
399        var row = (IndexedDataRow<T>)sender;
400        chart.Series[row.Name].Name = row.Name;
401      }
402    }
403    #endregion
404    #region Values Event Handlers
405    private void Values_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<Tuple<T, double>>> e) {
406      if (InvokeRequired)
407        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_ItemsAdded), sender, e);
408      else {
409        IndexedDataRow<T> row = null;
410        valuesRowsTable.TryGetValue((IObservableList<Tuple<T, double>>)sender, out row);
411        if (row != null) {
412          Series rowSeries = chart.Series[row.Name];
413          if (!invisibleSeries.Contains(rowSeries)) {
414            rowSeries.Points.Clear();
415            FillSeriesWithRowValues(rowSeries, row);
416            RecalculateAxesScale(chart.ChartAreas[0]);
417            UpdateYCursorInterval();
418          }
419        } else AddDataRow((IndexedDataRow<T>)sender);
420      }
421    }
422    private void Values_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<Tuple<T, double>>> e) {
423      if (InvokeRequired)
424        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_ItemsRemoved), sender, e);
425      else {
426        IndexedDataRow<T> row = null;
427        valuesRowsTable.TryGetValue((IObservableList<Tuple<T, double>>)sender, out row);
428        if (row != null) {
429          if (row.Values.Count == 0) {
430            RemoveDataRow(row);
431          } else {
432            Series rowSeries = chart.Series[row.Name];
433            if (!invisibleSeries.Contains(rowSeries)) {
434              rowSeries.Points.Clear();
435              FillSeriesWithRowValues(rowSeries, row);
436              RecalculateAxesScale(chart.ChartAreas[0]);
437              UpdateYCursorInterval();
438            }
439          }
440        }
441      }
442    }
443    private void Values_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<IndexedItem<Tuple<T, double>>> e) {
444      if (InvokeRequired)
445        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_ItemsReplaced), sender, e);
446      else {
447        IndexedDataRow<T> row = null;
448        valuesRowsTable.TryGetValue((IObservableList<Tuple<T, double>>)sender, out row);
449        if (row != null) {
450          if (row.Values.Count == 0) {
451            RemoveDataRow(row);
452          } else {
453            Series rowSeries = chart.Series[row.Name];
454            if (!invisibleSeries.Contains(rowSeries)) {
455              if (row.VisualProperties.ChartType == DataRowVisualProperties.DataRowChartType.Histogram) {
456                rowSeries.Points.Clear();
457                FillSeriesWithRowValues(rowSeries, row);
458              } else {
459                foreach (IndexedItem<Tuple<T, double>> item in e.Items) {
460                  rowSeries.Points[item.Index].SetValueXY(item.Value.Item1, item.Value.Item2);
461                }
462              }
463              RecalculateAxesScale(chart.ChartAreas[0]);
464              UpdateYCursorInterval();
465            }
466          }
467        }
468      }
469    }
470    private void Values_ItemsMoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<Tuple<T, double>>> e) {
471      if (InvokeRequired)
472        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_ItemsMoved), sender, e);
473      else {
474        IndexedDataRow<T> row = null;
475        valuesRowsTable.TryGetValue((IObservableList<Tuple<T, double>>)sender, out row);
476        if (row != null) {
477          Series rowSeries = chart.Series[row.Name];
478          if (!invisibleSeries.Contains(rowSeries)) {
479            rowSeries.Points.Clear();
480            FillSeriesWithRowValues(rowSeries, row);
481            RecalculateAxesScale(chart.ChartAreas[0]);
482            UpdateYCursorInterval();
483          }
484        }
485      }
486    }
487
488    private void Values_CollectionReset(object sender, CollectionItemsChangedEventArgs<IndexedItem<Tuple<T, double>>> e) {
489      if (InvokeRequired)
490        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_CollectionReset), sender, e);
491      else {
492        IndexedDataRow<T> row = null;
493        valuesRowsTable.TryGetValue((IObservableList<Tuple<T, double>>)sender, out row);
494        if (row != null) {
495          if (row.Values.Count == 0) {
496            RemoveDataRow(row);
497          } else {
498            Series rowSeries = chart.Series[row.Name];
499            if (!invisibleSeries.Contains(rowSeries)) {
500              rowSeries.Points.Clear();
501              FillSeriesWithRowValues(rowSeries, row);
502              RecalculateAxesScale(chart.ChartAreas[0]);
503              UpdateYCursorInterval();
504            }
505          }
506        }
507      }
508    }
509    #endregion
510    #endregion
511
512    #region Chart Event Handlers
513    private void chart_MouseDown(object sender, MouseEventArgs e) {
514      HitTestResult result = chart.HitTest(e.X, e.Y);
515      if (result.ChartElementType == ChartElementType.LegendItem) {
516        ToggleSeriesVisible(result.Series);
517      }
518    }
519    private void chart_MouseMove(object sender, MouseEventArgs e) {
520      HitTestResult result = chart.HitTest(e.X, e.Y);
521      if (result.ChartElementType == ChartElementType.LegendItem)
522        this.Cursor = Cursors.Hand;
523      else
524        this.Cursor = Cursors.Default;
525    }
526    private void chart_CustomizeLegend(object sender, CustomizeLegendEventArgs e) {
527      foreach (LegendItem legendItem in e.LegendItems) {
528        var series = chart.Series[legendItem.SeriesName];
529        if (series != null) {
530          bool seriesIsInvisible = invisibleSeries.Contains(series);
531          foreach (LegendCell cell in legendItem.Cells) {
532            cell.ForeColor = seriesIsInvisible ? Color.Gray : Color.Black;
533          }
534        }
535      }
536    }
537    #endregion
538
539    private void ToggleSeriesVisible(Series series) {
540      if (!invisibleSeries.Contains(series)) {
541        series.Points.Clear();
542        invisibleSeries.Add(series);
543      } else {
544        invisibleSeries.Remove(series);
545        if (Content != null) {
546
547          var row = (from r in Content.Rows
548                     where r.Name == series.Name
549                     select r).Single();
550          FillSeriesWithRowValues(series, row);
551          this.chart.Legends[series.Legend].ForeColor = Color.Black;
552          RecalculateAxesScale(chart.ChartAreas[0]);
553          UpdateYCursorInterval();
554        }
555      }
556    }
557
558    private void FillSeriesWithRowValues(Series series, IndexedDataRow<T> row) {
559      for (int i = 0; i < row.Values.Count; i++) {
560        var value = row.Values[i];
561        if (IsInvalidValue(value.Item2)) continue;
562        var point = new DataPoint();
563        point.SetValueXY(value.Item1, value.Item2);
564        if (i == row.Values.Count - 1) {
565          point.Label = series.Name;
566          point.MarkerStyle = MarkerStyle.Cross;
567          point.MarkerSize = 15;
568          point.MarkerBorderWidth = 1;
569        }
570        series.Points.Add(point);
571      }
572    }
573
574    #region Helpers
575    protected void RemoveCustomPropertyIfExists(Series series, string property) {
576      if (series.IsCustomPropertySet(property)) series.DeleteCustomProperty(property);
577    }
578
579    private ChartDashStyle ConvertLineStyle(DataRowVisualProperties.DataRowLineStyle dataRowLineStyle) {
580      switch (dataRowLineStyle) {
581        case DataRowVisualProperties.DataRowLineStyle.Dash:
582          return ChartDashStyle.Dash;
583        case DataRowVisualProperties.DataRowLineStyle.DashDot:
584          return ChartDashStyle.DashDot;
585        case DataRowVisualProperties.DataRowLineStyle.DashDotDot:
586          return ChartDashStyle.DashDotDot;
587        case DataRowVisualProperties.DataRowLineStyle.Dot:
588          return ChartDashStyle.Dot;
589        case DataRowVisualProperties.DataRowLineStyle.NotSet:
590          return ChartDashStyle.NotSet;
591        case DataRowVisualProperties.DataRowLineStyle.Solid:
592          return ChartDashStyle.Solid;
593        default:
594          return ChartDashStyle.NotSet;
595      }
596    }
597
598    /// <summary>
599    /// Determines whether a double value can be displayed (converted to Decimal and not an NaN).
600    /// </summary>
601    /// <param name="x">The number to check.</param>
602    /// <returns><code>true</code> if the value can be safely shwon in the chart,
603    /// <code>false</code> otherwise.</returns>
604    protected static bool IsInvalidValue(double x) {
605      return double.IsNaN(x) || x < (double)decimal.MinValue || x > (double)decimal.MaxValue;
606    }
607    #endregion
608  }
609}
Note: See TracBrowser for help on using the repository browser.