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.
- How can I do this ‘quick and dirty’ (like repaint).
- Is dependency properties the way to go on this?
- Is it worth it/always advisable, to create a wpf wrapper class for my FooBars?
Thanks…
Your type should implement
INotifyPropertyChangedso that a collection can detect the changes. As Sam says, passstring.Emptyas the argument.You also need to have the
ListBox‘s data source be a collection that provides change notification. This is done via theINotifyCollectionChangedinterface (or the not-so-WPFIBindingListinterface).Of course, you need the
INotifyCollectionChangedinterface to fire whenever one of the memberINotifyPropertyChangeditems fires its event. Thankfully there are a few types in the framework that provide this logic for you. Probably the most suitable one isObservableCollection<T>. If you bind yourListBoxto anObservableCollection<FooBar>then the event chaining will happen automatically.On a related note, you don’t have to use a
ToStringmethod just to get WPF to render the object in the way that you want. You can use aDataTemplatelike this: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.Itemscollection as your collection. This won’t do the binding required. You’re better off doing something like:I haven’t checked that code for compilation accuracy, but you get the gist.
EDIT 2 Using the
DataTemplateI gave above (I edited it to fit your code) fixes the problem.It seems strange that firing
PropertyChangeddoesn’t cause the list item to update, but then using theToStringmethod isn’t the way that WPF was intended to work.Using this DataTemplate, the UI binds correctly to the exact property.
I asked a question on here a while back about doing string formatting in a WPF binding. You might find it helpful.
EDIT 3 I’m baffled as to why this is still not working for you. Here’s the complete source code for the window I’m using.
Code behind:
XAML: