WPF ObservableCollection does not update?

advertisements

Can't seem to get an ObservableCollection to update. The TreeView shows empty. Error: this type of collectionview does not support changes to its sourcecollection from a thread differentfrom the dispatcher thread.

Class level var

public ObservableCollection<TSItem> tsItems { get; set; }

Initialize Components

tsItems = new ObservableCollection<TSItem>();
bwRun.DoWork += bwRun_DoWork;
InitializeComponent();
tvTest.ItemsSource = tsItems;

from the background worker I use the following method to add to the collection

 private void AddTreeViewItem(TSItem item)
 {
     tsItems.Add(item);
 }

xaml

<TreeView x:Name="tvTest" HorizontalAlignment="Left" Height="249" Margin="140,36,0,0" VerticalAlignment="Top" Width="257">
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Image Source="{Binding Icon}" />
                    <TextBlock Text="{Binding Header}" />
                </StackPanel>
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>


You should dispatch changes to UI thread:

 private void AddTreeViewItem(TSItem item)
 {
    Dispatcher.BeginInvoke(new Action(() => tsItems.Add(item)));
 }