2016-12-16 29 views
1

我正在編寫我的第一個通用Windows應用程序,目前正在試驗加速度計。 當前我正在顯示它在屏幕上顯示的數字,但我還想顯示一個圖形,以直觀的方式描繪這些值。 我在網上看到了一些圖表示例,但沒有一個接受實時數據流並將它顯示出來。加速度計數據的Windows通用應用程序實時圖表

基本上我想要的是一個繪製代表值的線條加速計輸出。

這是我第一次嘗試在Windows編程,我正在使用C#。

有沒有一種「適當」的方式來做這樣的事情?一個普遍接受的方法?

+1

OxyPlot也應該可以工作。 –

回答

3

使用WinRTXamlToolkit

enter image description here

XAML:

<Page 
    x:Class="App3.MainPage" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="using:App3" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:Charting="using:WinRTXamlToolkit.Controls.DataVisualization.Charting" 
    mc:Ignorable="d" Loaded="Page_Loaded"> 

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
     <Grid.RowDefinitions> 
      <RowDefinition Height="10*"></RowDefinition> 
      <RowDefinition Height="*"></RowDefinition> 
      <RowDefinition Height="*"></RowDefinition> 
     </Grid.RowDefinitions> 
     <Charting:Chart x:Name="chart1" Grid.Row="0"> 
      <Charting:LineSeries ItemsSource="{Binding Data}" 
           DependentValuePath ="Accel" 
           IndependentValuePath ="Timestamp" Margin="0"/> 
     </Charting:Chart> 
     <Button x:Name="btnStart" Content="START" Grid.Row="1" Click="btnStart_Click" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"></Button> 
     <Button x:Name="btnStop" Content="STOP" Grid.Row="2" Click="btnStop_Click" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"></Button> 
    </Grid> 
</Page> 

的MainPage:

public sealed partial class MainPage : Page 
{ 
    MyViewModel vm; 

    public MainPage() 
    { 
     this.InitializeComponent(); 
    } 

    private void Page_Loaded(object sender, RoutedEventArgs e) 
    { 
     vm = new MyViewModel(); 
     DataContext = vm; 
    } 

    private void btnStart_Click(object sender, RoutedEventArgs e) 
    { 
     vm.Start(); 
    } 

    private void btnStop_Click(object sender, RoutedEventArgs e) 
    { 
     vm.Stop(); 
    } 
} 

ViewModel:

public class MyViewModel 
{ 
    private Timer accelerometer; 
    private Random r; 

    private ObservableCollection<MyAccelModel> data; 
    public ObservableCollection<MyAccelModel> Data { get { return data; } } 

    public MyViewModel() 
    { 
     data = new ObservableCollection<MyAccelModel>(); 
     r = new Random(DateTime.Now.Millisecond); 
    } 

    public void Start() 
    { 
     accelerometer = new Timer(AccelDataCallback, null, 100, 500); 
    } 

    public void Stop() 
    { 
     accelerometer.Dispose(); 
    } 

    private async void AccelDataCallback(object state) 
    { 
     await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, 
      () => 
      { 
       data.Add(new MyAccelModel { Timestamp = DateTime.Now, Accel = r.NextDouble() }); 
      }); 
    } 
} 
相關問題