WinForms.Charting suppress autogenerating legend

2019-07-01 16:57发布

I am using the System.Windows.Forms.DataVisualization.Charting.Chart class to draw a chart with some data.

Now I want to suppress the automatic generation of entries within the legend and replace them with custom items. I have already found the way to add custom items but no way of suppressing the autogeneration.

My Code:

var legend = new Legend();
legend.LegendStyle = LegendStyle.Table;
legend.TableStyle = LegendTableStyle.Wide;
legend.IsEquallySpacedItems = true;
legend.IsTextAutoFit = true;
legend.BackColor = Color.White;
legend.Font = new Font(Config.FontFamily, 9);
legend.Docking = Docking.Bottom;
legend.Alignment = StringAlignment.Center;

legend.CustomItems.Add(new LegendItem("test", Color.Green, string.Empty));

ch.Legends.Add(legend);

Has anyone done something like this before?

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-07-01 17:19

Try doing it in this event:

private void chart1_CustomizeLegend(object sender, CustomizeLegendEventArgs e)
{
    e.LegendItems.Clear();
    // new stuff
}
查看更多
Lonely孤独者°
3楼-- · 2019-07-01 17:33

I know this is old but wanted to post this here in case someone wants a slightly different way to go about it, this is based off of Steve Wellens answer but instead of adding the items in the event it just removes the non custom ones.

    protected void chartarea1_CustomizeLegend(object sender, System.Web.UI.DataVisualization.Charting.CustomizeLegendEventArgs e)
    {
        int customItems = ((Chart)sender).Legends[0].CustomItems.Count();
        if (customItems>0)
        {
            int numberOfAutoItems = e.LegendItems.Count()-customItems;
            for (int i = 0; i < numberOfAutoItems; i++)
            {
                e.LegendItems.RemoveAt(0);
            }
        }

    }
查看更多
做个烂人
4楼-- · 2019-07-01 17:35

Go to the Series collection in the chart properties, and find the IsVisibleInLegend property and set it to false

查看更多
登录 后发表回答