2012-01-17 89 views
0

我從xml中獲取一些數據,每隔2分鐘更新一次異步WebRequest。所以我需要每次數據更改列表框相應地改變。我從互聯網上獲取數據,最後一行代碼就是這些。當綁定屬性發生更改時,用綁定值更新列表框

IEnumerable<Update> list = from y in xelement.Descendants("Song") 
        select new Update() 
        { 
         NowTitle = y.Attribute("title").Value, 
         NowArtist = y.Element("Artist").Attribute("name").Value 
        }; 
        Dispatcher.BeginInvoke(()=> nowList.ItemsSource = list); 

XAML看起來像這樣。

 <ListBox x:Name="nowList" Height="86" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> 
       <ListBox.ItemTemplate> 
        <DataTemplate> 
         <StackPanel Margin="0,0,0,0" Orientation="Vertical" Background="Gray" HorizontalAlignment="Stretch"> 
          <TextBlock Height="Auto" Width="480" Text="{Binding Path=NowTitle, Mode=OneWay}" TextWrapping="Wrap" TextAlignment="Center" FontSize="24" FontWeight="Bold" Foreground="#FFE5D623" HorizontalAlignment="Stretch" /> 
          <TextBlock Height="Auto" Width="480" Text="{Binding Path=NowArtist, Mode=OneWay}" TextWrapping="Wrap" TextAlignment="Center" FontSize="24" FontWeight="Bold" Foreground="#FFE5D623" HorizontalAlignment="Stretch" /> 
         </StackPanel> 
        </DataTemplate> 
       </ListBox.ItemTemplate> 
      </ListBox> 

該類包含屬性的更新是這樣的。

public class Update : INotifyPropertyChanged 
{ 

    string nowTitle; 
    string nowArtist; 
    public string NowTitle 
    { 
     get 
     { 
      if (!string.IsNullOrEmpty(nowTitle)) 
      { 
       return "Τώρα : " + nowTitle; 
      } 
      else 
      { 
       return "something"; 
      } 
     } 
     set { this.nowTitle = value; 
     NotifyPropertyChanged("NowTitle"); 
     } 
    } 
    public string NowArtist 
    { 
     get 
     { 
      if (!string.IsNullOrEmpty(nowTitle)) 
      { 
       return "by " + nowArtist; 
      } 
      else 
      { 
       return ""; 
      } 
     } 
     set { this.nowArtist = value; 
     NotifyPropertyChanged("NowArtist"); 
     } 
    } 


    #region INotifyPropertyChanged Members 
    public event PropertyChangedEventHandler PropertyChanged; 
    public void NotifyPropertyChanged(String propertyName) 
    { 
     PropertyChangedEventHandler handler = PropertyChanged; 
     if (null != handler) 
     { 
      handler(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 
    #endregion 

} 

有誰能告訴我我做錯了什麼?謝謝!

+0

你調用Dispatcher.BeginInvoke(()=> nowList.ItemsSource = list);每次更新XML時都會調用? – 2012-01-17 16:03:17

+0

是的,它是webrequest回調的一部分,每次都執行。 – Kwstas 2012-01-17 16:04:47

回答

2

兩件事情,第一,請確保您的nowList屬性提升屬性更改事件,第二,請確保您的nowList的類型是ObservableCollection<Update>

<edit> 

如果nowList是你的列表框,那就是更多的則可能是你的culprite 。嘗試做一個ObservableCollection<Update>作爲引發改變事件的性質,然後在你的XAML的列表框綁定到...

<ListBox ItemSource={Binding myList}/> 

我比較肯定,這將解決您的問題

</edit> 
+0

屬性在Update類中實現INotifyPropertyChanged接口。 nowList是一個ListBox。 – Kwstas 2012-01-17 16:07:47

+0

@Kwstas你設置nowList的ItemsSource的行 - 它應該是一個ObservableCollection ,但它是一個IEnumerable 2012-01-18 01:16:27

相關問題