Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

mschart - Microsoft Chart Controls Legend Item Ordering

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...