如何在运行时刷新ListBox
本文关键字:刷新 ListBox 运行时 | 更新日期: 2023-09-27 18:25:22
我正在开发一个Windows Phone应用程序。我有一个由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; }
}
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>
看看这两行:
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);
}