首页 > 解决方案 > 在 C# Winforms 中使用 MouseEvents 更改图表系列的外观

问题描述

我的表格中有一个点图,它是动态创建的,因此图表上系列的编号/名称可以在表格的每次运行中发生变化。我希望能够使用图例突出显示一个系列,以便更好地查看仅属于该系列的点。我已经能够使用较厚的标记边框突出显示该系列,但我无法做到这一点,以便在再次单击或移出图例项时删除此突出显示。以下是我如何突出选定系列中的要点:

            private void plot.MouseMove (object sender, MouseEventArgs e)
                    {
                        HitTestResult result = plot.HitTest(e.X, e.Y);
                        if (result != null && result.Object != null)
                        {
                            if (result.ChartElementType == ChartElementType.LegendItem)
                            {
                                string selseries = result.Series.Name;
                                plot.Series[selseries].MarkerBorderWidth = 3;
                                plot.Series[selseries].MarkerSize = 11;
                                plot.Series[selseries].MarkerBorderColor = Color.Black;
                            }
                        }

                    };

突出显示后如何取消选择它?与其他系列相比,有没有更好的方法来选择性地突出一个系列?理想情况下,我希望将除所选系列之外的所有系列更改为较暗的颜色,从而突出显示相关系列,但我会满足于能够选择/取消选择相关系列。

标签: c#visual-studiowinformschartslegend

解决方案


要“记住”您突出显示的系列,您需要在此方法之外存储一个引用,以便以后可以访问它。然后,每当您想清除更改时,只需查找您之前保存的任何内容并重置属性。这是一些示例代码:

string selectedSeries = "";     // store a class-scoped reference

private void plot.MouseMove(object sender, MouseEventArgs e)
{
    HitTestResult result = plot.HitTest(e.X, e.Y);
    if (result != null && result.Object != null && result.ChartElementType == ChartElementType.LegendItem)
    {
        string selseries = result.Series.Name;

        // store a reference to what we are changing:
        selectedSeries = selseries;

        plot.Series[selseries].MarkerBorderWidth = 3;
        plot.Series[selseries].MarkerSize = 11;
        plot.Series[selseries].MarkerBorderColor = Color.Black;
    }
    else
    {
        // if we clear the selection here, then we are clearing the selection
        // whenever we move off the legend item... that was one of your use cases
        // you could also do something similar in a mouse click event to cover your other use case.

        if (selectedSeries != "")
        {
            plot.Series[selectedSeries].MarkerBorderWidth = 1; // set these to default value
            plot.Series[selectedseries].MarkerSize = 5;
            plot.Series[selectedseries].MarkerBorderColor = Color.Green;
            selectedSeries = ""; // reset selection
        }
    }
}

推荐阅读