【发布时间】:2012-01-17 15:49:05
【问题描述】:
我从一个 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>
包含属性的类Update就是这个。
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
}
谁能告诉我我做错了什么?谢谢!
【问题讨论】:
-
每次更新 XML 时是否都调用
Dispatcher.BeginInvoke(()=> nowList.ItemsSource = list);部分? -
是的,它是 webrequest 回调的一部分,并且每次都会执行。
标签: xaml windows-phone-7 data-binding httpwebrequest