我正在开发一个Windows Phone应用程序。我有一个ListBox,从JSON文件填充。
这个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; }
}
ListBox 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>
答案 0 :(得分: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);
}