The main reason I started with WPF in the first place was the promise of all the awesome possibilities of databinding. After days of headaches I'm beginning to think that one of the most common scenarios is impossible, and I'd love to be proved wrong! :)
- I have a ListBox that will have instances of my custom class as its ListItems.
- My class is DataBinding-ready by implementing some DependencyProperties.
- My ListBox has a custom DataTemplate to display these properties in a nice layout.
- ListBox has the ItemsSource set to an
ObservableCollection<MyClass>
- The listbox may need to display hundreds, even thousands of items so in order to maintain a responsive UI, they need to be instantiated in the background.
Turns out it's impossible to create instances of my class in a background thread and add them to the ObservableCollection (or directly to the listbox, when we omit the ItemsSource) in the UI thread, as long as they are DependencyObjects. It throws an exception saying
Must create DependencySource on same Thread as the DependencyObject
How am I supposed to handle a scenario like this in WPF? Don't use DPs at all and go with INotifyPropertyChanged? What people actually do, when they need to do this? I think this is a fairly common scenario and I'm quite upset how most DataBinding related articles ramble about the possibility to change a TextBox background color if you type in "Magenta"... :)