Alex Rivera | Logout

Updating WPF list when item changes

Asked 2009-02-16T12:24:15.057
17

I have a WPF ListBox, and I've added some 'FooBar' objects as items (by code). FooBars aren't WPF objects, just dumb class with an overwritten ToString() function.

Now, when I change a property which influences the ToString, I'd like to get the ListBox to update.

  1. How can I do this 'quick and dirty' (like repaint).
  2. Are dependency properties the way to go on this?
  3. Is it worth it/always advisable, to create a WPF wrapper class for my FooBars?
Edit
Report

2 Answers

15

Your type should implement INotifyPropertyChanged so that a collection can detect the changes. As Sam says, pass string.Empty as the argument.

You also need to have the ListBox's data source be a collection that provides change notification. This is done via the INotifyCollectionChanged interface (or the not-so-WPF IBindingList interface).

Of course, you need the INotifyCollectionChanged interface to fire whenever one of the member INotifyPropertyChanged items fires its event. Thankfully there are a few types in the framework that provide this logic for you. Probably the most suitable one is ObservableCollection<T>. If you bind your ListBox to an ObservableCollection<FooBar> then the event chaining will happen automatically.

On a related note, you don't have to use a ToString method just to get WPF to render the object in the way that you want. You can use a DataTemplate like this:

<ListBox x:Name="listBox1">
    <ListBox.Resources>
        <DataTemplate DataType="{x:Type local:FooBar}">
            <TextBlock Text="{Binding Path=Property}"/>
        </DataTemplate>
    </ListBox.Resources>
</ListBox>

In this way you can control the presentation of the object where it belongs -- in the XAML.

EDIT 1 I noticed your comment that you're using the ListBox.Items collection as your collection. This won't do the binding required. You're better off doing something like:

var collection = new ObservableCollection<FooBar>();
collection.Add(fooBar1);

_listBox.ItemsSource = collection;

I haven't checked that code for compilation accuracy, but you get the gist.

EDIT 2 Using the DataTemplate

answered 2009-02-16T13:25:38.530
1

Try implementing the INotifyPropertyChanged interface on your FooBar objects. When they change, raise PropertyChanged events, passing string.Empty as the property name. That should do the trick.

answered 2009-02-16T12:49:08.320

Your Answer