locked
ObservableCollection Binding in WPF RRS feed

  • Question

  • I'm new to WPF binding and I'm trying to read each line from a text file using a StringBuilder to manipulate each line, convert the result to a String, add the string to an ObservableCollection and display each line in a ListBox as it's added.  Everything is working except the dynamic update to the ListBox.  The ListBox displays the entire collection after the whole file is read but I'd like it to show each addition as it's added.

    I expected that ObservableCollection's implementation of INotifyCollectionChanged would enable the binding to update the ListBox after each addtion, but that's not the case.  I've searched for answers but can't find an example that does just this.  Do I need to have a separate class derived from String that implements INotifyPropertyChanged?  If so, how might I do that?  Below is the binding I use:

    Thanks for responding,

    jphiggs

     

     

     

    <ListBox x:Name="ListBox1"  Margin="10,10,10,64" ItemsSource="{Binding Source={StaticResource oc}}" IsSynchronizedWithCurrentItem="true" />

     

    Monday, October 11, 2010 5:17 PM

Answers

  • Thanks Reed.  You're right about the single method / single thread.  I'll try using a background thread.

    jphiggs

    • Marked as answer by jphiggs Tuesday, October 12, 2010 2:37 AM
    Tuesday, October 12, 2010 2:37 AM

All replies

  • "I expected that ObservableCollection's implementation of INotifyCollectionChanged would enable the binding to update the ListBox after each addtion, but that's not the case."

     

    This should work.  Adding an item to an ObservableCollection<T> will get reflected in the UI.


    However, I suspect that the problem is that you're adding these in a single method, on a single thread.  The UI will not update as long as you prevent it from processing messages, so if you add these in a loop on the UI thread, it won't be able to refresh until your method completes, at which point every string will be there.


    You could push this onto a background thread, but be aware that you'll need to marshal the call to add to the collection onto the UI thread, since INotifyCollectionChanged doesn't automatically marshal across threads like INotifyPropertyChanged.

     



    Reed Copsey, Jr. - http://reedcopsey.com
    • Proposed as answer by noorbakhsh Monday, October 11, 2010 8:37 PM
    Monday, October 11, 2010 6:04 PM
  • Thanks Reed.  You're right about the single method / single thread.  I'll try using a background thread.

    jphiggs

    • Marked as answer by jphiggs Tuesday, October 12, 2010 2:37 AM
    Tuesday, October 12, 2010 2:37 AM