0

嗨,我从 xml 加载我的数据,我想将第一个项目绑定到我的文本块,但是当我尝试给 DataContext = myclass.articles[0] 时,它会抛出错误,因为它的加载未编译。类架构应该如何?加载时如何绑定数据。

 public class ArticleViewModel
{

    public ArticleViewModel()
    {
        articles = new ObservableCollection<Article>();
    }
    public ObservableCollection<Article> articles;

    public void LoadArticle(int Cat_ID)
    {
        DownloadFile("http://www.loadarticle.com/Rss.asp?id=" + Cat_ID);
     }
    public  string xml;
    public  void DownloadFile(string url)
    {
        string sonuc = "";
        WebClient wc = new WebClient();
        wc.DownloadStringCompleted += wc_DownloadStringCompleted;
        wc.DownloadStringAsync(new Uri(url));
     }

    void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        xml = e.Result;
        XDocument doc = XDocument.Parse(xml);
        var articless = (from i in doc.Element("rss").Element("channel").Elements()
                    where i.Name == "item"
                    select new Article { Baslik = i.Element("title").Value, Detay = i.Element("description").Value });

        foreach (Article artic in articless)
        {
            this.articles.Add(artic);
        }


    }

页面.Xaml.cs

    protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);

        string kategori_refno = "";
        if (NavigationContext.QueryString.TryGetValue("kategori_refno", out kategori_refno))
        {
            ArticleViewModel fm = new ArticleViewModel();
            fm.LoadArticle(Convert.ToInt32(kategori_refno));

                DataContext = fm.articles[0];
        }
    }

Xaml

  <TextBlock x:Name="tbKategori_Adi" Text="{Binding Baslik,Mode=TwoWay}" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/> 
<TextBlock x:Name="tbFikra" TextWrapping="Wrap" Text="{Binding Detay,Mode=TwoWay}" Margin="0,0,0,70"/>
4

1 回答 1

0

有几件事:

  1. 让整个页面的 DataContext 成为 ArticleViewModel。
  2. 研究使用INotifyPropertyChanged接口在数据绑定更改时通知 UI
  3. 我会有一个名为 FirstArticle 的属性或类似的属性,你将TextBlocks 绑定到。然后在数据成功下载后填充此属性。再加上 INotifyPropertyChanged,您将在加载数据时更新 UI。
于 2013-01-23T06:12:01.367 回答