c# - Microsoft 图表控件和 X 轴时间刻度格式

标签 c# .net winforms mschart

我的 winforms 应用程序中有一个 Microsoft 图表控件。

我目前在循环中播放 X 和 y 值。我还将 X 轴格式设置为

ChartAreas[0].AxisX.LabelStyle.Format={"00:00:00"}

这作为一种时间格式工作得很好,但是我注意到一旦我的时间值超过 60 秒(即 00:00:60),而不是比例上升到 1 分钟(即 00:01:00)它在进入一分钟 (00:00:99) 然后 (00:01:00) 之前进入 61(即 00:00:61)一直到 99

请问有办法解决这个问题吗?

最佳答案

我怀疑 LabelStyle.Format 属性的使用方式与 string.Format(mySringFormat,objToFormat) 类似。
因此,假设您的底层 X 对象类型是 double,它只会打印一个 冒号分隔 double(例如 4321 将是 00:43:21).

据我所知,没有一种简单的方法可以仅使用字符串格式来打印 double 值,例如时间值。

如果您可以更改填充图表的代码,我建议您为 X 值传递 DateTime,然后您就可以使用自定义 DateTime格式化,例如

“HH:mm:ss”,或 others

编辑:

根据您的评论:

// create a base date at the beginning of the method that fills the chart.
// Today is just an example, you can use whatever you want 
// as the date part is hidden using the format = "HH:mm:ss"
DateTime baseDate = DateTime.Today; 

var x = baseDate.AddSeconds((double)value1);
var y = (double)value2;
series.Points.addXY(x, y);

编辑 2:

这是一个完整的示例,将此逻辑应用到您的代码中应该很容易:

private void PopulateChart()
{
    int elements = 100;

    // creates 100 random X points
    Random r = new Random();
    List<double> xValues = new List<double>();
    double currentX = 0;
    for (int i = 0; i < elements; i++)
    {
        xValues.Add(currentX);
        currentX = currentX + r.Next(1, 100);
    }

    // creates 100 random Y values
    List<double> yValues = new List<double>();
    for (int i = 0; i < elements; i++)
    {
        yValues.Add(r.Next(0, 20));
    }

    // remove all previous series
    chart1.Series.Clear();

    var series = chart1.Series.Add("MySeries");
    series.ChartType = SeriesChartType.Line;
    series.XValueType = ChartValueType.Auto;

    DateTime baseDate = DateTime.Today;
    for (int i = 0; i < xValues.Count; i++)
    {
        var xDate = baseDate.AddSeconds(xValues[i]);
        var yValue = yValues[i];
        series.Points.AddXY(xDate, yValue);
    }

    // show an X label every 3 Minute
    chart1.ChartAreas[0].AxisX.Interval = 3.0;
    chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Minutes;

    chart1.ChartAreas[0].AxisX.LabelStyle.Format = "HH:mm:ss";
}

关于c# - Microsoft 图表控件和 X 轴时间刻度格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5605852/

相关文章:

.net - .NET 4.0 的契约设计与 Eiffel 相比如何?

c# - 该命令需要至少两行源数据

.net - 有没有办法让 App.config 文件引用另一个完整的配置文件? (。网)

c# - 如何对绑定(bind)到 EF EntityCollection<T> 的 WinForms DataGridView 进行排序

c# - 向面板添加垂直滚动条

.net - 是否可以为 Visual Basic WinForms 项目设置项目范围的表单主题?

c# - 如何使用 Sqlite.Net 扩展过滤器

c# - MySQL Provider 和 ASP.NET MVC 5 的成员资格问题,未考虑 minRequiredNonalphanumericCharacters

c# - 使用 linq 将逗号分隔的字符串转换为列表

c# - 如何在 WPF 中使用 MVVM 将 Windows 窗体控件绑定(bind)到 "Grid"面板