2012-01-17 87 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

相关问题