【问题标题】:MsChart: How to display Calendar week number as labels on the the X-axis?MsChart:如何将日历周数显示为 X 轴上的标签?
【发布时间】:2011-08-10 10:10:44
【问题描述】:

我需要在 MSChart 中格式化时间轴的标签,例如“CW21”、“CW22”……我苦苦挣扎了一段时间,但还没有找到任何解决方案。

  1. 有一个 LabelStyle.Format 属性,但这不支持 (AFAIK) 日历周。它使用 DateTime 格式化字符串。有没有办法引入自定义格式化程序?

  2. 在框架中我找到了Calendar.GetWeekOfYear 方法,它可以为我提供正确的周数。现在的问题是如何将这些组合在一起?

有什么好的策略可以以通用方式在轴上设置自己的标签吗? (事先不知道轴的最小/最大点)

【问题讨论】:

    标签: c# .net format mschart


    【解决方案1】:

    是的,您可以使用Chart.FormatNumber 事件,例如:

    private void FillChart()
    {
        // register the format event
        this.chart1.FormatNumber += new EventHandler<FormatNumberEventArgs>(chart1_FormatNumber);
    
        // fill the data table with values
        DataTable dt = new DataTable();
        dt.Columns.Add("X", typeof(DateTime));
        dt.Columns.Add("Y", typeof(double));
    
        dt.Rows.Add(DateTime.Today.AddDays(1), 10);
        dt.Rows.Add(DateTime.Today.AddDays(8), 30);
        dt.Rows.Add(DateTime.Today.AddDays(15), 10);
        dt.Rows.Add(DateTime.Today.AddDays(21), 20);
        dt.Rows.Add(DateTime.Today.AddDays(25), 40);
        dt.Rows.Add(DateTime.Today.AddDays(31), 25);
    
        // bind the data table to chart
        this.chart1.Series.Clear();
    
        var series = this.chart1.Series.Add("Series 1");
        series.XValueMember = "X";
        series.YValueMembers = "Y";
    
        series.ChartType = SeriesChartType.Line;
        this.chart1.DataSource = dt;
        this.chart1.DataBind();
    
        // set a custom format to recognize the AxisX label in the event handler
        this.chart1.ChartAreas[0].AxisX.LabelStyle.Format = "CustomAxisXFormat"; 
    
    }
    
    void chart1_FormatNumber(object sender, FormatNumberEventArgs e)
    {
        if (e.ElementType == ChartElementType.AxisLabels &&
            e.Format == "CustomAxisXFormat")
        {
            if (e.ValueType == ChartValueType.DateTime)
            {
                var currentCalendar = CultureInfo.CurrentCulture.Calendar;
                e.LocalizedValue = "CW" +
                    currentCalendar.GetWeekOfYear(DateTime.FromOADate(e.Value),
                    System.Globalization.CalendarWeekRule.FirstDay,
                    CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek);
            }
        }
    }
    

    结果如下:

    【讨论】:

    • 谢谢你!我怀疑轴类级别的事件(没有),但我没有看图表类!你拯救了我的一天!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    相关资源
    最近更新 更多