XAML Databinding Issue ?

Recently, I started having problems with the error "Items collection must be empty before using ItemsSource" popping up after I’d made a few changes to my UI.  I think I understand the root trigger, but I haven’t got time to reason through the entire cause and effect chain.  So here’s my best guess…..

In simplest terms, I have a list of widgets, and when any widget is selected, the selection handler then causes another list to get populated with the attributes of the selected widget.  There’s a twist to this however.  The list of attributes is not sourced from the selection made from the widget list, it’s sourced from a specific property of that selection.

I’ve got the widget list – I click on an item, it fires some logic, and I set the value of SelectedWidget, which is a property I fire an OnPropertyChanged for, i.e. I call the bound PropertyChangedEventHandler with “SelectedWidget”.  Specifically, I implement the INotifyPropertyChanged interface with this code;

    • public void OnPropertyChanged(string name)
    • {
      • PropertyChangedEventHandler handler = PropertyChanged;
      • if (handler != null)
      • {
        • handler(this, new PropertyChangedEventArgs(name));
      • }
    • }

Inside the selection changed handler for the Widget list,  I called OnPropertyChanged(“SelectedWidget”);

Now I’ve got another listbox in the display, and this one is databound in XAML by setting ItemsSource to

ItemsSource="{Binding Path=SelectedWidget.WidgetAttributes, ElementName=_widgetcatalog}"
      

The key element to note is that the ItemsSource is set to a property of the SelectedWidget, not to the SelectedWidget itself….  Seems that this bothers XAML – it doesn’t affect it with simple scalar controls, i.e. I have text boxes bound to SelectedWidget.Name and SelectedWidget.RevisionDate, but it seems to get upset when I do this trick with a list box.

This may also have something to do with the template that underlies the attribute display list, I’m not claiming to be exactly certain – I just know that when I made the selection event handler in the code behind clear out the item binding, then clear out the list of attributes, and then reset the item binding to the new selection, everything worked fine – if I performed the equivalent action in XAML through simple databinding, no such luck….

YMMV – take this with a grain of salt – I just posted this because I got so few hits on that error message I figured a guess was better than nothing……  It kinda bugs me because I like the fact that databound controls in the form SomePropertyINotifyOn.ThePropertyThatActuallyHasTheDataIShow is really handy, you just notify when the root property changes and everybodies happy as far as scalar data displays (textboxes, etc) are concerned – the list box didn’t seem to like this approach so much

 

Published Saturday, February 02, 2008 8:27 PM by MarkMMullin
Filed Under: ,

Comments