【发布时间】:2017-07-08 12:12:55
【问题描述】:
我正在做一个基于 WPF Charting Toolkit 的应用程序实时数据图表。我通过串口获取数据。 设置图表代码如下:
<chartingToolkit:Chart Margin="10,10,10,0" ClipToBounds="True" x:Name="chart1" Title="Chart Title">
<chartingToolkit:LineSeries IndependentValueBinding="{Binding Value1}" DependentValueBinding="{Binding Value2}" ItemsSource="{Binding}" Background="Transparent" Cursor="No">
<chartingToolkit:LineSeries.DataPointStyle>
<Style TargetType="{x:Type chartingToolkit:LineDataPoint}">
<Setter Property="Height" Value="0"/>
<Setter Property="Width" Value="0" />
<Setter Property="Background" Value="Green"/>
</Style>
</chartingToolkit:LineSeries.DataPointStyle>
</chartingToolkit:LineSeries>
</chartingToolkit:Chart>
效果很好,但我仍然需要设置 X 轴的最大值和最小值。 X值(Value1)是接收样本的数量,Y轴值(Value2)显然是接收样本的具体值。
我的问题是关于 X 轴范围的。
目前,我得到的最小值为 0,最大值为串口当前接收到的最大样本数。
但我想设置一个我想看到的 X 轴的永久范围。
例如我想在 X 轴范围内查看 500 个样本。
表示当样本数超过500时,max应为最高样本数,min应max-500。
主要难点是如何在WPF中设置实时数据??
谁能帮帮我好吗?
更新问题
在@jstreet 建议之后,我正在更新我的问题。
我有这个方法在 MainWindow 类的单独线程中运行,如下所示。
public partial class MainWindow : Window
{
public SerialPort serialPort1 = new SerialPort();
public string rx_str = "";
public string rx_str_copy;
public int a;
public double x, y;
ObservableCollection<ChartData> chartData;
ChartData objChartData;
Thread myThread;
public MainWindow()
{
InitializeComponent();
string[] port = SerialPort.GetPortNames();
foreach (string a in port)
{
comboPorts.Items.Add(a);
}
Array.Sort(port);
comboPorts.Text = port[0];
objChartData = new ChartData();
chartData.Add(objChartData);
chart1.DataContext = chartData;
myThread = new Thread(new ThreadStart(Run));
}
public void Run()
{
while (true)
{
serialPort1.Write("a");
rx_str = serialPort1.ReadTo("b");
rx_str_copy = rx_str;
x = a;
y = Double.Parse(rx_str_copy, CultureInfo.InvariantCulture);
a++;
Dispatcher.Invoke(new Action(delegate
{
chartData.Add(new ChartData() { Value1 = x,
Value2= y });
}));
}
}
这个 Run() 方法负责接收数据并将其添加到图表中。
在另一个类中,我处理了对即将到来的数据和设置属性 Valeu1 和 Value2 的反应:
public class ChartData : INotifyPropertyChanged
{
double _Value1;
double _Value2;
public double Value1
{
get
{
return _Value1;
}
set
{
_Value1 = value;
OnPropertyChanged("Value1");
}
}
public double Value2
{
get
{
return _Value2;
}
set
{
_Value2 = value;
OnPropertyChanged("Value2");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new
PropertyChangedEventArgs(propertyName));
}
}
}
如何使@jstreet 的解决方案适应我的背后代码示例??
【问题讨论】:
标签: c# wpf xaml charts wpftoolkit