我制作了一个从数据库中提取数据的 WPF 图。我需要数据在日期更改时自动更改。
这是我的代码:
XAML 代码:
<DVC:Chart Name="callLogs"
Background="SteelBlue"
Margin="136,0,0,0"
Title="Calls Per Hour"
BorderBrush="Transparent">
<DVC:Chart.LegendStyle>
<Style TargetType="Control">
<Setter Property="Width" Value="0"/>
<Setter Property="Height" Value="0"/>
</Style>
</DVC:Chart.LegendStyle>
<DVC:Chart.Axes>
<DVC:LinearAxis Orientation="Y" Title="Ammount of calls" ShowGridLines="True"/>
</DVC:Chart.Axes>
<DVC:Chart.Series>
<DVC:ColumnSeries Title="Calls per Hour"
IndependentValueBinding="{Binding Path=Key}"
DependentValueBinding="{Binding Path=Value}">
</DVC:ColumnSeries>
</DVC:Chart.Series>
</DVC:Chart>
<DatePicker x:Name="Datepicker1" HorizontalAlignment="Left"
Margin="10,21,0,0"
VerticalAlignment="Top"
Width="126"
BorderBrush="Transparent"
SelectedDateFormat="Short"/>
C#代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using System.Windows.Controls.DataVisualization;
using System.Windows.Controls.Primitives;
using System.Windows.Controls.DataVisualization.Charting;
namespace MainWindow
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
LoadColumnChartData();
}
private void LoadColumnChartData()
{
Datepicker1.SelectedDate = DateTime.Today;
string pickDate = Datepicker1.SelectedDate.Value.ToString("yyyy-MM-dd");
int[] callCounter = new int[100];
int[] callHour = new int[100];
int counter = 0;
SqlConnection sqlConnection1 = new SqlConnection("Server=nl-reportserver;Database=RealConnect;User Id=sa;Password=<password>");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.Parameters.Add("@pickDate", pickDate);
cmd.CommandText = "SELECT * FROM RC_callsperhour where convert(date,call_logdate,120) = convert(date,@pickDate,120) order by callhour";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
callHour[counter] = reader.GetInt32(2);
callCounter[counter] = reader.GetInt32(3);
counter++;
}
}
else
{
MessageBox.Show("No rows found.");
}
reader.Close();
sqlConnection1.Close();
((ColumnSeries)callLogs.Series[0]).ItemsSource = Enumerable.Range(0, counter).Select(i => new KeyValuePair<int, int>(callHour[i], callCounter[i])).ToArray();
}
}
}
请注意,出于安全目的,我已从 sql 连接中删除了密码。
我该怎么做呢?