我需要从网站获取数据并将这些数据放入我Listbox
的 Xaml 中。我正在使用 Windows Phone。
这是我的 c# 函数:
private void DownLoadCompleted(object sender, HtmlDocumentLoadCompleted e)
{
ObservableCollection<PopularVideos> _popVideos = new ObservableCollection<PopularVideos>();
var data = e.Document.DocumentNode.SelectSingleNode("//div[@class='content']")
.Descendants("img")
.Select(img => new PopularVideos()
{
Titulo = img.Attributes["alt"].Value,
Url = img.Attributes["src"].Value,
}).ToList();
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
foreach (var item in data)
{
_popVideos.Add(new PopularVideos(item.Titulo, item.Url));
}
});
}
类PopularVideos
:
public class PopularVideos
{
public PopularVideos() { }
public PopularVideos(string titulo, string url)
{
Titulo = url;
Url = url;
}
public string Titulo { get; set; }
public string Url { get; set; }
}
Listbox
在 Xaml 中:
<ListBox Name="listBoxPopular" ItemsSource="{Binding Mode=OneWay}" DataContext="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Image Name="imagem" Source="{Binding Path=Url}"/>
<TextBlock Text="{Binding Path=Title}" Tap="HyperlinkButton_Tap" FontSize="30" Foreground="#FF159DDE" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
这段代码没有显示错误,但我的Listbox
仍然是空的。
主页代码隐藏中的源代码:
namespace AppUnno
{
public partial class MainPage : PhoneApplicationPage
{
int aux = 3;
private List<Artista> _artistas;
public class MyDataContextClass
{
public ObservableCollection<PopularVideos> PopVideos;
public MyDataContextClass()
{
ObservableCollection<PopularVideos> PopVideos = new ObservableCollection<PopularVideos>();
}
private void DownLoadCompleted(object sender, HtmlDocumentLoadCompleted e)
{
PopVideos.Clear();
// Add to pop Videos.
}
}
// Constructor
public MainPage()
{
if (NetworkInterface.GetIsNetworkAvailable())
{
InitializeComponent();
ConsultaArtista("http://www.unnu.com/music-artists");
//ConsultaPopularVideos("http://www.unnu.com/popular-music-videos");
panorama.Visibility = Visibility.Collapsed;
// Set the data context of the listbox control to the sample data
DataContext = App.ViewModel;
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
carregaFeed();
ApplicationBarra(aux);
HtmlWeb.LoadAsync("http://www.unnu.com/popular-music-videos", DownLoadCompleted);
}
else
{
var result = MessageBox.Show("There are problems in your connection. Please verify your connection and try again!", "", MessageBoxButton.OK);
aux = 1;
ApplicationBarra(aux);
}
}
private void DownLoadCompleted(object sender, HtmlDocumentLoadCompleted e)
{
PopVideos.Clear();
var data = e.Document.DocumentNode.SelectSingleNode("//div[@class='content']")
.Descendants("img")
.Select(img => new PopularVideos()
{
Titulo = img.Attributes["alt"].Value,
Url = img.Attributes["src"].Value,
}).ToList();
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
foreach (var item in data)
{
PopVideos.Add(new PopularVideos(item.Titulo, item.Url));
}
});
}
错误是 DownloadCompleted 函数中的“PopVideos”:
*
“当前上下文中不存在名称‘PopVideos’”
*