Richard Gavel

April 17, 2009

Silverlight ComboBox and Asynchronous Population of Underlying Data

Filed under: Silverlight — richardgavel @ 9:31 am
Tags:

I have a Silverlight application that makes use of the ViewModel pattern in which most of the data entity maintenance screens include combo boxes whose ItemSource and SelectedItem are bound to properties on the view model. However, there appears to be a temporal coupling between the ItemsSource and SelectedItem properties such that the ComboBox breaks if the SelectedItem does not exist in the ItemsSource. I would get exceptions complaining about a null reference exception on getting the data context, for example. Research showed several posts noting that having the XAML property for ItemsSource after the XAML property for SelectedItem would cause issues.

Because the underlying ItemsSource for my combo boxes were based upon database data and not fixed data, compounded by the async nature of Silverlight, I could not guarantee the ItemsSource would be populated prior to binding the SelectedItem. So I decided to bind the SelectedItem in code. Upon loading the form, if the underlying collection was non-null, I bound the SelectedItem property. Otherwise, I attached a PropertyChanged listener so I could defer the binding until the collection was populated.

this.Loaded += (loadedSource, loadedArgs) =>
    {
        ActivityMaintenanceModel model = (ActivityMaintenanceModel)this.DataContext;

        if (model.ProfileChoices != null)
            ProfileSelector.SetBinding(ComboBox.SelectedItemProperty, new Binding("Activity.Profile") { Mode = BindingMode.TwoWay });
        else
        {
            model.PropertyChanged += (propertyChangedSource, propertyChangedArgs) =>
                {
                    if (propertyChangedArgs.PropertyName == "ProfileChoices")
                        ProfileSelector.SetBinding(ComboBox.SelectedItemProperty, new Binding("Activity.Profile") { Mode = BindingMode.TwoWay });
                };
        }
    };

One possible cleaner solution would be a custom binding on the SelectedItem that could defer the actual binding until certain circumstances existed, such as the ItemsSource being populated.

Technorati Tags:
About these ads

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

The Rubric Theme. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: