如何异步更新可观察的集合

时间:2015-09-02 08:59:00

标签: c# wpf xaml observablecollection

更新ObservableCollection是否是一个好方法?这段代码中是否隐藏着任何危险?

namespace WpfApplication142
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            DataContext = new GetData();
            InitializeComponent();
        }
    }
    public class GetData
    {
        public ObservableCollection<string> Items {get;set;}
        public GetData()
        {
            Items = new ObservableCollection<string>();
            Items.Add("one");
            var task = Task.Factory.StartNew(() =>
                {
                    UpdateItems();
                });
            task.ContinueWith(delegate { Items.Add("two"); }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
        }
        public void UpdateItems()
        {
            System.Threading.Thread.Sleep(10000);
        }
    }
}

Xaml代码看起来像这样

<Grid>
    <ListView ItemsSource="{Binding Items}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <Label Content="{Binding .}"></Label>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Grid>

0 个答案:

没有答案