Silverlight 4 ComboBox - Binding to Nullable data (tried TargetNullValue but not working as expected)
(Please note - I am a Silverlight beginner and am looking for the simplest solution 开发者_StackOverflow社区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:
No option is selected in the ComboBox (its blank)
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>
I ended up using a Converter that converts the Null in the bound object to zero in the ComboBox and then back again ... like the one mentioned here http://forums.silverlight.net/forums/t/195627.aspx
精彩评论