C#實現圖表中鼠標移動並顯示數據
本文實例為大傢分享瞭C#實現圖表中鼠標移動並顯示數據的具體代碼,供大傢參考,具體內容如下
效果圖:
1.首先在頁面上添加一個label控件並 默認隱藏:
2.給該圖表添加MouseMove鼠標移動事件:
/// <summary> /// 鼠標經過時發生 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void chart1_MouseMove(object sender, MouseEventArgs e) { try { HitTestResult Result = new HitTestResult(); Result = chart1.HitTest(e.X, e.Y); if (Result.Series != null && Result.Object != null) { // 獲取當前焦點x軸的值 string xValue = ObjectUtil.GetPropertyValue(Result.Object, "AxisLabel").ToString(); // 獲取當前焦點所屬區域名稱 string areaName = ObjectUtil.GetPropertyValue(Result.Object, "LegendText").ToString(); // 獲取當前焦點y軸的值 double yValue = Result.Series.Points[Result.PointIndex].YValues[0]; // 鼠標經過時label顯示 skinLabel4.Visible = true; skinLabel4.Text = "時間:"+ xValue + "\n"+ areaName + ":"+ yValue + "ug/m^3"; skinLabel4.Location = new Point(e.X, e.Y - 20); } else { // 鼠標離開時label隱藏 skinLabel4.Visible = false; } } catch (Exception se) { // 鼠標離開時label隱藏 skinLabel4.Visible = false; } }
3.其中GetPropertyValue() 獲取對象中的某個屬性 方法如下:
public class ObjectUtil { /// <summary> /// 獲取某個對象中的屬性值 /// </summary> /// <param name="info"></param> /// <param name="field"></param> /// <returns></returns> public static object GetPropertyValue(object info, string field) { if (info == null) return null; Type t = info.GetType(); IEnumerable<System.Reflection.PropertyInfo> property = from pi in t.GetProperties() where pi.Name.ToLower() == field.ToLower() select pi; return property.First().GetValue(info, null); } }
另外(以下與上述無關)圖表添加數據後綁定提示:
/// <summary> /// 揚塵監測、噪音監測、溫度檢測、濕度監測 /// </summary> /// <param name="_Chart"></param> private void ChartTemperatureMethod(Chart _Chart) { List<string> xData = new List<string>() {"0", "4:00", "8:00", "12:00", "16:00", "20:00", "24:00" }; List<int> yData = new List<int>() { 0,21, 35, 48, 40, 27, 7 }; List<int> yData1 = new List<int>() { 0,5, 18, 25, 68, 50, 30 }; string iss = "#VALX"; // 需要提示的信息 chart1.Series["Series1"].ToolTip = "時間:#VALX\nPM2.5:#VALYug/m^3\tPM10:" + yData1[xData.IndexOf("#VALX") + 1] + "ug/m^3"; // 標簽顯示 Inside:內部,Outside:外部,Disabled:禁用 chart1.Series["Series1"]["PieLabelStyle"] = "Outside"; chart1.Series["Series1"].Points.DataBindXY(xData, yData); // 需要提示的信息 chart1.Series["Series2"].ToolTip = "時間:#VALX\nPM2.5:" + yData[xData.IndexOf("#VALX") + 1] + "ug/m^3\tPM10:#VALYug/m^3"; // 標簽顯示 Inside:內部,Outside:外部,Disabled:禁用 chart1.Series["Series2"]["PieLabelStyle"] = "Outside"; chart1.Series["Series2"].Points.DataBindXY(xData, yData1); }
以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。