C1Chart for WPF轴:ToolTip显示鼠标所在位置的日期信息
在上一章日期轴的显示中,我们介绍了如何设置X轴为日期类型。
本文就在此基础上,介绍如何展示日期类型的Tooltip。
添加标记标签
在添加标记标签前,请阅读代码添加标记文章,按照文章所示内容给图表添加标记。
按照提示的步骤通过如下代码给图表添加标记,使得鼠标Hover的时候,可以显示数据信息。
var sp = new StackPanel(); var tb1 = new TextBlock(); var bind1 = new Binding(); bind1.Source = obj; bind1.StringFormat = "x={0:#.##}"; bind1.Path = new PropertyPath("DataPoint.X"); tb1.SetBinding(TextBlock.TextProperty, bind1); var tb2 = new TextBlock(); var bind2 = new Binding(); bind2.Source = obj; bind2.StringFormat = "y={0:#.##}"; bind2.Path = new PropertyPath("DataPoint.Y"); tb2.SetBinding(TextBlock.TextProperty, bind2); sp.Children.Add(tb1); sp.Children.Add(tb2); bdr.Child = sp;
但是由于X轴是日期轴(OADate),此时节点的换算会不正确。 对于这个问题,需要自定义一个DateConverter。
DateConverter
从IValueConverter接口继承,自定义Datetime的Converter,将doulbe的value转成DateTime类型。
这里需要用到DateTime.FromOADate方法进行转换。
参考如下:
public class DateTimeConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { double v = (double)value; DateTime dt; if (!double.IsNaN(v)) { dt = DateTime.FromOADate(v); } else { dt = DateTime.Now; } return dt; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } }
给Binding设置converter
这个时候需要第一步里添加的标记标签的代码进行更改,给X轴设置我们上一步实现的Converter。
代码参考:
var bind1 = new Binding(); bind1.Source = obj; bind1.StringFormat = "x={0:yyyy/MM/dd}"; bind1.Converter = new DateTimeConverter(); bind1.Path = new PropertyPath("DataPoint.X");
实现的效果如下:
示例参考:
ChartWPF_DateTooltip.zip (17.01 kb)
更多资源
C1Chart的在线英文产品文档地址:
http://helpcentral.componentone.com/nethelp/c1wpfchart/#!Documents/componentonechartforwpf.htm
如果你对C1Chart感兴趣,请到我们的官网下载最新版本:/developer/componentone-winform/controls/chart
如果你有疑问,可以到GCDN论坛获得技术支持:http://gcdn.grapecity.com.cn/showforum-68.html
另外,更多信息,欢迎阅读《C1Chart for WPF初级教程》系列文章: