Связывание UWP ObservableCollection с диаграммой и кнопкой - PullRequest
0 голосов
/ 19 декабря 2018

У меня есть два элемента управления на данной странице: график и кнопка.Цель кнопки - выйти / закрыть страницу.Диаграмма постоянно обновляется раз в секунду, поскольку показания температуры добавляются в коллекцию ObservableCollection.

Я не могу покинуть страницу.Однажды секунда не выглядит особенно занятой, и я подумал бы, что у пользовательского интерфейса была бы гибкость, чтобы обработать щелчок, чтобы закрыть страницу. График / диаграмма, которую я использую, это Ailon Quickcharts, если это имеет значение.

using System;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using IOT_Sensors;
using atlas_iot;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Diagnostics;
using Windows.Security.Cryptography.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using IOT_Sensors;
using System.Globalization;
using IOT_sensors_3.Data;


namespace atlas_iot
{
public sealed partial class RTD_graph : Page , INotifyPropertyChanged
{
    private string name;
    private Module RTD;
    private bool send_text = false;

    private ObservableCollection<RealTimeTempDataItemGraph> _realTimeTempDataGraphs;

    public ObservableCollection<RealTimeTempDataItemGraph> RealTimeTempDataGraphs
    {
        get { return _realTimeTempDataGraphs; }
        set { _realTimeTempDataGraphs = value; RaisePropertyChanged(nameof(RealTimeTempDataGraphs)); }
    }
    private DispatcherTimer _timer = new DispatcherTimer();

    public RTD_graph()
    {
        this.InitializeComponent();
        Unloaded += MainPage_Unloaded;
        this.DataContext = this;

        _timer.Interval = TimeSpan.FromSeconds(1);
        _timer.Tick += Timer_Tick;
        _timer.Start();
    }

    public class RealTimeTempDataItemGraph
    {
        public int Seconds { get; set; }
        public float Visits { get; set; }
    }

    private void MainPage_Unloaded(object sender, object args)
    {
        /* Cleanup */
        _timer.Stop();
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        _timer = new DispatcherTimer
        {
            Interval = TimeSpan.FromMilliseconds(500)
        };
        _timer.Tick += Timer_Tick;

        if (e.Parameter is Module)
        {
            RTD = (Module)e.Parameter;
            RTD.StartReadingPoll();
            _timer.Start();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void RaisePropertyChanged(string name)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }


    private void Timer_Tick(object sender, object e)
    {
        if (RTD.NewResponseComplete())Q
        {
          //  CentralAreaScreen.FontSize = 160;
            string abc = RTD.GetLastResponse();
            double n;
            bool isNumeric = double.TryParse(abc, out n);
            if (isNumeric)
            {
                if (n > 0)
                {
                    string myText = RTD.GetLastResponse();
                    float.TryParse(myText, NumberStyles.Any, 
CultureInfo.InvariantCulture, out float temp_var);
                    RealTimeTempDataGraphs.Add(new 
RealTimeTempDataItemGraph(){Seconds = 100,Visits = temp_var});
                }
            }

            send_text = false;
        }
        else if (RTD.NewReadingComplete() && (send_text == false))
        {
            // CentralAreaScreen.FontSize = 160;
            // CentralAreaScreen.Text = RTD.GetLastReading().ToString();
            string myText = RTD.GetLastReading().ToString();

            float.TryParse(myText, NumberStyles.Any, CultureInfo.InvariantCulture, out float temp_var);
            RealTimeTempDataGraphs.Add(new RealTimeTempDataItemGraph() { Seconds = 10, Visits = temp_var });

        }
    }

    private async Task Home_btn_ClickAsync(object sender, RoutedEventArgs e)
    {
        await HomebtnClickAsync();

    }


    public async Task HomebtnClickAsync()
    {
        // Do asynchronous work.
        await Task.Delay(1000);
    }
}
 }


My XAML:
<Page
x:Class="atlas_iot.RTD_graph"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:IOT_sensors_3"
xmlns:qc="using:Ailon.QuickCharts"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" FontFamily="Arial"  Height="480" Width="800"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">


<Grid Name="BlowPop" Width="800" Height="500" HorizontalAlignment="Center" VerticalAlignment="Bottom">
    <Grid.Background>
        <ImageBrush Stretch="Fill" ImageSource="Assets/RTD.png" />
    </Grid.Background>
    <Button x:Name="Home_btn" Content="" HorizontalAlignment="Left" Height="55" Margin="17,408,0,0" VerticalAlignment="Top" Width="55"  >
        <Button.Background>
            <ImageBrush Stretch="Fill" ImageSource="Assets/home.png" />
        </Button.Background>
    </Button>


    <ScrollViewer HorizontalScrollMode="Enabled" VerticalScrollMode="Enabled" Padding="125"  >
        <qc:SerialChart DataSource="{Binding RealTimeTempDataGraphs}" CategoryValueMemberPath="Seconds" Background="Silver" Foreground="Black" PlotAreaBackground="Silver">
            <qc:SerialChart.Graphs>

                <qc:LineGraph Title="Realtime Temperature" ValueMemberPath="Visits" Background="Silver"  Brush="Red" />
            </qc:SerialChart.Graphs>
        </qc:SerialChart>
    </ScrollViewer>
</Grid>

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...