2014-10-01 81 views
0

我正在開發Windows Phone應用程序。我有一個ListBox,從JSON文件填充。在運行時如何刷新ListBox?

這個JSON文件,我從Web服務器獲得。當我將應用程序與服務器同步時,ListBox不會自動填充(爲空)。需要退出應用程序並返回ListBox來顯示數據。

所以,我還沒有找到一種方法來在運行時「刷新」我的ListBox。

同步按鈕:

 private void sinc(object sender, EventArgs e) 
    { 

     IsolatedStorageSettings iso = IsolatedStorageSettings.ApplicationSettings; 

     if (iso.TryGetValue<string>("isoServer", out retornaNome)) 
     { 
      serv = retornaNome; 


      client = new WebClient(); 
      url = serv + "/json.html"; 
      Uri uri = new Uri(url, UriKind.RelativeOrAbsolute); 
      client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted); 
      client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged); 
      client.OpenReadAsync(uri); 
     } 

     else 
     { 
      MessageBox.Show("Configure um servidor antes de sincronizar os dados!"); 
      NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.RelativeOrAbsolute)); 

     } 
    } 

解析JSON:

  try 
     { 
      using (var store = IsolatedStorageFile.GetUserStoreForApplication()) 
      using (var readStream = new IsolatedStorageFileStream("json.html", FileMode.Open, FileAccess.Read, FileShare.Read, store)) 
      using (var reader = new StreamReader(readStream)) 
      { 
       text = reader.ReadToEnd(); 
      } 
      { 


       DataContext = this; 

       // String JSON 
       string json = text; 

       // Parse JObject 
       JArray jObj = JArray.Parse(json); 

       Items = new ObservableCollection<Fields>(
    jObj.Children().Select(jo => jo["result"]["fields"].ToObject<Fields>())); 

      } 


     } 
     catch (Exception) 
     { 
      MessageBox.Show("A lista de produtos será exibida somente após a sincronização dos dados!"); 

     } 

public ObservableCollection<Fields> Items { get; set; } 

    public class Fields 
    { 

     [JsonProperty(PropertyName = "FId")] 
     public int FId { get; set; } 

     public string FNome { get; set; } 
     public float FEstado1 { get; set; } 
     public string FPais { get; set; } 
     public string Quantity { get; set; } 
     public string lero { get; set; } 
     public string Quantity1 { get; set; } 
     public string FEstado { get; set; } 

    } 

列表框XAML:

<ListBox Name="List1" ItemsSource="{Binding Items}" Margin="0,85,0,0" > 
        <ListBox.ItemTemplate> 
         <DataTemplate> 
          <Grid> 
           <Grid.ColumnDefinitions> 
            <ColumnDefinition Width="242" /> 
            <ColumnDefinition Width="128" /> 
            <ColumnDefinition Width="Auto" /> 
           </Grid.ColumnDefinitions> 
           <StackPanel Hold="holdListAdd" Margin="0,0,-62,17" Grid.ColumnSpan="3"> 
            <StackPanel.Background> 
             <SolidColorBrush Color="#FF858585" Opacity="0.5"/> 
            </StackPanel.Background> 
            <TextBlock x:Name="NameTxt" Grid.Column="0" Text="{Binding FNome}" TextWrapping="Wrap" FontSize="40" Style="{StaticResource PhoneTextExtraLargeStyle}"/> 
            <TextBlock Grid.Column="1" Text="{Binding FEstado}" TextWrapping="Wrap" Margin="45,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/> 

           </StackPanel> 
           <TextBlock Grid.Column="0" Text="R$" Margin="15,48,158,17" Style="{StaticResource PhoneTextSubtleStyle}"/> 
          </Grid> 
         </DataTemplate> 
        </ListBox.ItemTemplate> 
        <ListBox.ItemContainerStyle> 
         <Style TargetType="ListBoxItem"> 
          <Setter Property="HorizontalContentAlignment" Value="Stretch"/> 
         </Style> 
        </ListBox.ItemContainerStyle> 
       </ListBox> 
+1

如何'Items'屬性定義? – Dennis 2014-10-01 12:21:01

+0

抱歉@丹尼斯,我編輯了我的問題。我在「解析JSON」的末尾寫道。 – 2014-10-01 12:28:47

回答

2

看看這兩條線:

public ObservableCollection<Fields> Items { get; set; } 

Items = new ObservableCollection<Fields>(
    jObj.Children().Select(jo => jo["result"]["fields"].ToObject<Fields>())); 

既然你改變Items財產,你應該通知視圖要麼是這樣的:

public ObservableCollection<Fields> Items 
{ 
    get { return items; } 
    set 
    { 
     if (items != value) 
     { 
      items = value; 
      OnPropertyChanged("Items"); 
     } 
    } 
} 
private ObservableCollection<Fields> items; 

或本(如果你不想改變財產申報):

Items = new ObservableCollection<Fields>(/* fill the collection */); 
OnPropertyChanged("Items"); // this is enough for the view to re-read property value 

另一種做你想做的事情的方法是不改變屬性的值,而是改變它的的內容。這是假設,即Items集合已經創建,你只需要調用Clear,然後Add每一個結果,這是從服務器加載:

public ObservableCollection<Fields> Items 
{ 
    get 
    { 
     return items ?? (items = new ObservableCollection<Fields>()); 
    } 
} 
private ObservableCollection<Fields> items; 

var newItems = jObj.Children().Select(jo => jo["result"]["fields"].ToObject<Fields>()); 
Items.Clear(); 
foreach (var item in newItems) 
{ 
    Items.Add(item); 
} 
+0

感謝您的回答。什麼是「OnPropertyChanged」?沒有在我的代碼中聲明。 – 2014-10-01 13:50:33

+0

這是典型的'INotifyPropertyChanged'實現的一部分(通過此接口視圖模型通知有關屬性值更改的視圖):http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged%28v=vs 0.110%29.aspx – Dennis 2014-10-01 14:13:01