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

放肆的年华 提交于 2019-12-11 16:34:44

问题


(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>

回答1:


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



来源:https://stackoverflow.com/questions/4639751/silverlight-4-combobox-binding-to-nullable-data-tried-targetnullvalue-but-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!