我正在尝试使用动态数据显示制作图形。我正在使用MVVM。我的senderviewmodel代码是以下
voltagePointCollection = new VoltagePointCollection();
updateCollectionTimer = new DispatcherTimer();
updateCollectionTimer.Interval = TimeSpan.FromMilliseconds(1);
updateCollectionTimer.Tick += new EventHandler(updateCollectionTimer_Tick);
updateCollectionTimer.Start();
var ds = new EnumerableDataSource<VoltagePoint>(voltagePointCollection);
ds.SetXMapping(x => dateAxis.ConvertToDouble(x.Date));
ds.SetYMapping(y => y.Voltage);
((MainWindow)System.Windows.Application.Current.MainWindow).TextBlock1.Text = "Setting Text from My Program";
((MainWindow)System.Windows.Application.Current.MainWindow).plotter.AddLineGraph(ds, Colors.Green, 2, "Volts");
plotter.AddLineGraph(ds, Colors.Green, 2, "Volts"); // to use this method you need "using Microsoft.Research.DynamicDataDisplay;"
MaxVoltage = 3;
MinVoltage = -3;
//System.IO.StreamReader file = new System.IO.StreamReader("C:\Users\niranjan\Desktop\sample.txt");
//var sample = file.ReadToEnd();
//tokens = sample.Split(new string[] { "rn", "n" }, StringSplitOptions.None);
// here graph ending
ResultValue = "N/D";
var wasSent = await _senderBluetoothService.Send(SelectDevice, Data);
if (wasSent)
{
ResultValue = "The data was sent.";
}
else
{
ResultValue = "The data was not sent.";
}
我的view.xaml文件是以下
<d3:ChartPlotter Name= "plotter" Grid.Row="1" Grid.Column="1" Height="244" HorizontalAlignment="Left" Width="1076">
<d3:ChartPlotter.HorizontalAxis>
<d3:HorizontalDateTimeAxis Name="dateAxis"/>
</d3:ChartPlotter.HorizontalAxis>
<d3:Header FontFamily="Georgia" Content="Voltage chart"/>
<d3:VerticalAxisTitle FontFamily="Georgia" Content="Voltage [V]" />
<d3:HorizontalAxisTitle FontFamily="Georgia" Content="Time"/>
<d3:HorizontalLine Value="{Binding MaxVoltage}" Stroke="Red" StrokeThickness="2"/>
<d3:HorizontalLine Value="{Binding MinVoltage}" Stroke="Red" StrokeThickness="2"/>
</d3:ChartPlotter>
线路出现问题
plotter.AddLineGraph(ds, Colors.Green, 2, "Volts");
它表示绘图仪在当前上下文中不存在。但是绑定MaxVoltage和MinVoltage是有效的。你能告诉我一些更改吗?这样我就可以在SenderViewmodel.cs文件中使用plotter.addline了。
使用MVVM时,不能直接针对UI元素。与UI交互的唯一方法是使用ViewModel属性并将其与UI绑定。你正在使用Max和MinVoltage,所以这些工作。。。
但绘图仪是一个UI元素,如果你想使用它的任何方法,最好的方法是使用某种MVVM消息传递(MVVM light messenger),并在视图的代码后面注册到该消息。这样就可以使用UI元素。
您可以在视图中声明viewModel的实例,并将其绑定到视图的DataContext,如下所示:
public MyViewModel myVM;
添加到视图的构造函数:
public MyView()
{
..
myVM = new MyViewModel();
this.DataContext = myVM;
}
在视图中声明绘图仪,并在此处使用视图中的数据Model作为数据源,然后调用绘图函数:
var ds = new EnumerableDataSource<VoltagePoint>(myVM.voltagePointCollection);
ds.SetXMapping(x => dateAxis.ConvertToDouble(x.Date));
ds.SetYMapping(y => y.Voltage);
plotter.AddLineGraph(ds, Colors.Green, 2, "Volts");
希望能有所帮助。你有问题吗?我交给你处理。
致问候,