Microsoft Chart Controls Legend Item Ordering

2019-01-28 22:11发布

I've got a chart with 8 series - call them S1 through S8. They're in order in the chart's list of series, and they're presented using custom legend items (Legend.CustomItems). Everything works fine, except there seems to be a bug with how items are displayed in the legend when the legend wraps around to a new line.

I'd like the items to be displayed in rows:

S1 S2 S3 S4
S5 S6 S7 S8

Unfortunately, it seems like when the legend detects that it's going to take two rows, it fills in vertically before horizontally, like so:

S1 S3 S5 S7
S2 S4 S6 S8

Is there any way to get the items arranged properly? Is this a bug with the controls?

var chart = new Chart();
// More chart setup
foreach(var s in chart.Series)
{
    if (simpleLegend) chart.Legends[0].CustomItems.Add(s.Color, s.LegendText);
    else
    {
        var legendItem = new LegendItem();
        // Legend item customization
        chart.Legends[0].CustomItems.Add(legendItem);
    }
}

EDIT

To make it clear, the issue is with the layout of the legend items, not the order. Depending on the length of the legend items, I may end up with this layout:

S1 S3 S5 S7 S8
S2 S4 S6

1条回答
成全新的幸福
2楼-- · 2019-01-28 22:41

You can arrange them in CustomizeLegend event.

Add OnCustomizeLegend="Chart1_CustomizeLegend" to your Chart markup or bind it in code behind. Then create handler:

protected void Chart1_CustomizeLegend(object sender, CustomizeLegendEventArgs e)
{
    //change order of legend items
    var items = e.LegendItems;
    var item = items[1]; //s2
    items.RemoveAt(1);
    items.Insert(2, item);
    item = items[1]; //after removing s2, s3 is now here
    items.RemoveAt(1);
    items.Insert(4, item);
    //etc...
}

Or you can create some collection first and fill it by referencing existing legend items in desired order, then clearing LegendItems and inserting all items at once. I think you can write it in a way it will be valid for all items number, but I leave it to you ;).

More info: http://msdn.microsoft.com/en-us/library/dd488245.aspx

(I know this question is almost 2 years old but maybe someone with same problem (like me today) will find this helpful.)

查看更多
登录 后发表回答