How to control winform mschart legend text alignment c#?

后端 未结 3 853
误落风尘
误落风尘 2021-01-21 19:06

How does one set the alignment of text within a chart legend object? I\'ve tried using:

 myChartName.Legends[\"mySeriesName\"].Alignment = stringAlignment.Near 
         


        
3条回答
  •  情话喂你
    2021-01-21 20:06

    Problem solved. The CustomItem approach wasn't working either, so I tried using the LegendCellColumn Class.

    I changed the LegendStyle from Column to Row, then added two CellColumns, one for the series symbol and one for the legend text. Set the alignment, margins, and column widths (that turned out to be the trick), and voila; a legend that looks like I want. Here's the code for anyone with a similar issue.

    chartSel.Legends[ySeries.Name].CellColumns.Add(new LegendCellColumn("", LegendCellColumnType.SeriesSymbol, ""));
    chartSel.Legends[ySeries.Name].CellColumns[0].Alignment = ContentAlignment.TopLeft;
    chartSel.Legends[ySeries.Name].CellColumns[0].Margins = new System.Windows.Forms.DataVisualization.Charting.Margins(0, 0, 1, 1);
    chartSel.Legends[ySeries.Name].CellColumns[0].MinimumWidth = 250;
    chartSel.Legends[ySeries.Name].CellColumns[0].MaximumWidth = 250;
    
    chartSel.Legends[ySeries.Name].CellColumns.Add(new LegendCellColumn("", LegendCellColumnType.Text, ySeries.Name));
    chartSel.Legends[ySeries.Name].CellColumns[1].Alignment = ContentAlignment.MiddleLeft;
    chartSel.Legends[ySeries.Name].CellColumns[1].Margins = new System.Windows.Forms.DataVisualization.Charting.Margins(0, 0, 1, 1);
    chartSel.Legends[ySeries.Name].CellColumns[1].MinimumWidth = 1500;
    chartSel.Legends[ySeries.Name].CellColumns[1].MaximumWidth = 1500;
    

    It's probably not the most efficient way to do it, but it works. Technically, the legend symbol and text are still centered in the object, but because I'm forcing the widths of the two columns it has the appearance of being left-justified.

    Hopefully, this may help another newbie like me avoid days of consternation.

提交回复
热议问题