2014-10-01 68 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