Silverlight 4 ComboBox - Binding to Nullable data (tried TargetNullValue but not working as expected)

Posted by Laurence on Stack Overflow See other posts from Stack Overflow or by Laurence
Published on 2011-01-09T14:41:55Z Indexed on 2011/01/09 14:53 UTC
Read the original article Hit count: 263

Filed under:

(Please note - I am a Silverlight beginner and am looking for the simplest solution here, e.g. that doesn't involve writing/installing a replacement for the ComboBox control!)

This is an issue with a Silverlight 4 application that uses the View Model (MVVM) approach. I have a simple form for editing a "Product" object. Product has a CategoryID property which is nullable (int?). A ComboBox is used to view and set the CategoryID - this is bound to an ObservableCollection of Categories. Product also has number of non-nullable properties bound to TextBoxes.

I want the user to see "N/A" in the ComboBox for a product with no category, and to be use this "N/A" option to set CategoryID to null. So, I manually added a Category object with CategoryID=0 and CategoryName="N/A" to the collection; then I set TargetNullValue=0 in the SelectedValue Binding of the ComboBox. My thinking was - when the ComboBox SelectedValue was bound to a null CategoryID it would substitute zero, and therefore select the "N/A" option.

When editing a Product with a non-null CategoryID, everything works. However when a null CategoryID is found, two problems occur:

  1. No option is selected in the ComboBox (its blank)

  2. The ComboBox binding seems broken from this point onwards - any Product I subsequently edit (incl. ones with a non-null CategoryID) have nothing selected in the ComboBox (its still populated with all categories - just no selected item).

I've seen reports of problem #2 (here, here) but I was under the impression that #1 should have worked.

What am I missing to get the "N/A" option to be selected?

XAML for ComboBox:

<ComboBox x:Name="cboCategory" ItemsSource="{Binding colCategories, Mode=OneWay}" SelectedValuePath="CategoryID" DisplayMemberPath="CategoryName" SelectedValue="{Binding CurrentProduct.CategoryID, Mode=TwoWay, TargetNullValue=0}" Height="24" Width="344"></ComboBox>

© Stack Overflow or respective owner

Related posts about silverlight-4.0