我需要逐个填充列表框 就像要填充一个项目的列表而不是1/5秒之后,其他项目将被添加到列表中
任何想法如何做到(在wpf中)?
答案 0 :(得分:2)
如果将ListBox绑定到ObservableCollection<T>
,则只能从UI线程修改集合。因此,您可以使用DispatcherTimer
,在UI线程上引发Tick
事件,或使用像this one这样的专门集合,并从另一个线程填充
答案 1 :(得分:0)
在窗口或控件的Loaded事件中,执行方法以加载第一项数据 通过调用System.Windows.Threading.DispatcherObject的BeginInvoke方法 UI元素,并指定Background的System.Windows.Threading.DispatcherPriority。什么时候 此方法已完成生成数据并将其添加到列表中,添加相同的方法 Dispatcher的队列递归,每次只添加一个项目然后排队 使用DispatcherPriority of Background添加下一个。
private ObservableCollection<string> numberDescriptions;
// Declare a delegate to wrap the LoadNumber method
private delegate void LoadNumberDelegate(int number);
private void LoadNumber(int number)
{
// Add the number to the observable collection
// bound to the ListBox
numberDescriptions.Add("Number " + number.ToString());
if(number < 10000)
{
// Load the next number, by executing this method
// recursively on the dispatcher queue, with
// a priority of Background.
//
this.Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new LoadNumberDelegate(LoadNumber), ++number);
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// Initialize an ObservableCollection of strings
numberDescriptions =
new ObservableCollection<string>();
// Set it as the ItemsSource for the ListBox
listBox.ItemsSource = numberDescriptions;
// Execute a delegate to load
// the first number on the UI thread, with
// a priority of Background.
//
this.Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new LoadNumberDelegate(LoadNumber), 1);
}
请参阅WPF Recipes in C# 2008异步加载ListBox中的项目(第460页)
答案 2 :(得分:0)
以下是如何使用DataTemplate将列表框与RSS源绑定的示例:
<UserControl.Resources>
<XmlDataProvider x:Key ="DataRSS" XPath="//item" Source="http://rss.feedsportal.com/c/629/f/502199/index.rss"></XmlDataProvider >
</UserControl.Resources >
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<ListBox ItemsSource="{Binding Source={StaticResource DataRSS}}" Height="516" Margin="0,0,32,0" Background="{x:Null}" BorderBrush="#FF627DAE">
<ListBox.ItemTemplate >
<DataTemplate >
<Grid Width="400" Height="100" >
<Image Source="{Binding XPath=enclosure/@url}" Grid.Column="0" HorizontalAlignment="Left" VerticalAlignment="Top" />
<TextBlock TextWrapping="Wrap" Text="{Binding XPath=title}" FontWeight="Bold" Grid.Column="2"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</grid>