簡體   English   中英

第一次調用該函數時,該函數不起作用(WP8)

[英]Function doesn't work when I call it except for the first time (WP8)

我的應用程序需要解析JSON文件才能從網上獲取信息。 當我加載該應用程序時,它可以正常工作,但是當我單擊“刷新”按鈕時,它不能正常運行。 有人可以看看代碼(C#),看看我在做什么錯嗎?

== MainPage.xaml ==

<phone:PhoneApplicationPage
    x:Class="BitValue.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot è la griglia radice in cui viene inserito tutto il contenuto della pagina-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!-- NOTA SULLA LOCALIZZAZIONE:
            Per localizzare le stringhe visualizzate copiarne i valori in chiavi denominate in modo appropriato
            nel file di risorse della lingua neutra dell'applicazione (AppResources.resx) quindi
            sostituire il valore del testo hard-coded tra le virgolette degli attributi
            con la clausola di binding il cui percorso punta a quel nome di stringa.

            Ad esempio:

                Text="{Binding Path=LocalizedResources.ApplicationTitle, Source={StaticResource LocalizedStrings}}"

            Questa associazione punta alla risorsa della stringa del modello denominata "ApplicationTitle".

            L'aggiunta delle lingue supportate nella scheda Proprietà progetto crea un
            nuovo file RESX per lingua che può trasportare i valori tradotti delle
            stringhe IU. L'associazione in questi esempi farà in modo che il valore degli
            attributi venga disegnato dal file RESX che corrisponde a
            CurrentUICulture dell'applicazione al momento del runtime.
         -->

        <!--TitlePanel contiene il nome dell'applicazione e il titolo della pagina-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock Text="BitValue" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - inserire ulteriore contenuto qui-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <StackPanel>
                <TextBlock HorizontalAlignment="Center">values provided by bitstamp</TextBlock>
                <Grid Grid.Column="4" Grid.Row="4" Margin="12,0,12,0">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="1*" ></ColumnDefinition>
                        <ColumnDefinition  Width="1*" ></ColumnDefinition>
                        <ColumnDefinition Width="1*" ></ColumnDefinition>
                        <ColumnDefinition  Width="1*" ></ColumnDefinition>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="1*"></RowDefinition>
                        <RowDefinition Height="1*"></RowDefinition>
                        <RowDefinition Height="1*"></RowDefinition>
                        <RowDefinition Height="1*"></RowDefinition>
                    </Grid.RowDefinitions>
                    <TextBlock Grid.Row="0" Text="LAST" Margin="5,10" Style="{StaticResource PhoneTextExtraLargeStyle}" Foreground="#FFEAB33C"/>
                    <TextBlock x:Name="valueLast"  Grid.Row="0" Margin="5,10" Grid.ColumnSpan="3" Grid.Column="1" Style="{StaticResource PhoneTextExtraLargeStyle}"/>

                    <TextBlock Grid.Column="0" Grid.Row="1" Text="BID" Margin="5,10" Foreground="#FF2AB437">
                    </TextBlock>

                    <TextBlock Grid.Column="2"  Grid.Row="1" Text="ASK" Margin="5,10" Foreground="#FFE83131">

                    </TextBlock>
                    <TextBlock Grid.Column="0" Grid.Row="2" Text="24H LOW" Foreground="#FFEAB33C" Margin="5,10"></TextBlock>

                    <TextBlock Grid.Column="2" Grid.Row="2" Text="24H HIGH" Foreground="#FFEAB33C" Margin="5,10"></TextBlock>

                    <TextBlock x:Name="ValueBid" Grid.Column="1" Grid.Row="1" Margin="5,10"></TextBlock>

                    <TextBlock x:Name="ValueAsk" Grid.Column="3" Grid.Row="1" Margin="5,10"></TextBlock>

                    <TextBlock x:Name="ValueLow" Grid.Column="1" Grid.Row="2" Margin="5,10"></TextBlock>

                    <TextBlock x:Name="ValueHigh" Grid.Column="3" Grid.Row="2" Margin="5,10"></TextBlock>

                </Grid>


            </StackPanel>
        </Grid>

        <!--Rimuovere il commento per vedere la griglia di allineamento che consenta di verificare che i controlli siano
            allineati ai limiti comuni.  L'immagine ha un margine superiore di -32px tenendo
            conto della barra delle applicazioni. Impostarlo su 0 (o eliminare tutti i margini)
            se la barra delle applicazioni è nascosta.

            Prima della spedizioni, eliminare questo XAML e l'immagine stessa.-->
        <!--<Image Source="/Assets/AlignmentGrid.png" VerticalAlignment="Top" Height="800" Width="480" Margin="0,-32,0,0" Grid.Row="0" Grid.RowSpan="2" IsHitTestVisible="False" />-->
    </Grid>
    <phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
            <shell:ApplicationBarIconButton IconUri="/Assets/refresh2.png" Text="refresh" Click="refreshClick"/>
            <shell:ApplicationBar.MenuItems>
                <shell:ApplicationBarMenuItem Text="about"/>
            </shell:ApplicationBar.MenuItems>
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>
</phone:PhoneApplicationPage>

== MainPage.xaml.cs ==

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using BitValue.Resources;
using System.Runtime.Serialization.Json;


namespace BitValue
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Costruttore
        public MainPage()
        {
            InitializeComponent();
            Loaded += OnLoaded;

            // Codice di esempio per localizzare la ApplicationBar
            //BuildLocalizedApplicationBar();
        }
                private void OnLoaded(object sender, RoutedEventArgs e)
        {
            refresh();
        }

        private void refreshClick(object sender, EventArgs e)
        {
            refresh();
        }


        private void refresh()
        {

            var webClient = new WebClient();

            webClient.OpenReadCompleted += OnOpenReadCompleted;

            webClient.OpenReadAsync(new Uri("https://www.bitstamp.net/api/ticker/", UriKind.Absolute));
        }

        private void OnOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            var serializer = new DataContractJsonSerializer(typeof(Result));
            var Result = (Result)serializer.ReadObject(e.Result);

            valueLast.Text = Result.LAST + " USD/BTC";
            ValueAsk.Text = Result.ASK;
            ValueBid.Text = Result.BID;
            ValueLow.Text = Result.LOW;
            ValueHigh.Text = Result.HIGH;
        }
    }

        // Codice di esempio per la realizzazione di una ApplicationBar localizzata
        //private void BuildLocalizedApplicationBar()
        //{
        //    // Imposta la barra delle applicazioni della pagina su una nuova istanza di ApplicationBar
        //    ApplicationBar = nuova ApplicationBar();

        //    // Crea un nuovo pulsante e imposta il valore del testo sulla stringa localizzata da AppResources.
        //    ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
        //    appBarButton.Text = AppResources.AppBarButtonText;
        //    ApplicationBar.Buttons.Add(appBarButton);

        //    // Crea una nuova voce di menu con la stringa localizzata da AppResources.
        //    ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
        //    ApplicationBar.MenuItems.Add(appBarMenuItem);
        //}
    }

== Result.cs ==

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;

namespace BitValue
{
    [DataContract]
    public class Result
    {
        [DataMember(Name = "last")]
        public string LAST
        {
            get;
            set;
        }
        [DataMember(Name = "ask")]
        public string ASK
        {
            get;
            set;
        }
        [DataMember(Name = "bid")]
        public string BID
        {
            get;
            set;
        }
        [DataMember(Name = "low")]
        public string LOW
        {
            get;
            set;
        }
        [DataMember(Name = "high")]
        public string HIGH
        {
            get;
            set;
        }
        [DataMember(Name = "timestamp")]
        public string TIMESTAMP
        {
            get;
            set;
        }
    }
}

提前致謝。

問題是您的代碼實際上看起來像。 好吧! 問題出在API內,您得到的是緩存的結果(所以第二次,緩存是由Webclient返回的)

在這里看看: WebClient / HttpClient的緩存問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM