I have a combobox in a WPF application with MVVM implemented. It looks like, -
<ComboBox x:Name="cboParent"
SelectedValuePath="FileId"
DisplayMemberPath="FileName"
IsEditable="True"
ItemsSource="{Binding Files}"
MaxDropDownHeight="125"
SelectedValue="{Binding Path=SelectedFile.ParentFileId}"
SelectedItem="{Binding Path=SelectedParentFile, Mode=TwoWay}" Height="26"/>
The Files collection is having a self referential key as ParentFileId. Now sometime this ParentFileId would be zero; meaning there is no parent file. In that case, I would expect that though the dropdown will have all the files but there will not be any SelectedItem.
But in reality am getting the SelectedFile as the SelectedItem in the ComboBox.
Can I get the ComboBox without anything selected when the ParentFileId is zero?
(I do not want to add any placeholder File in the collection of Files with FileId as zero.)
First, the explanation why this doesn't work out of the box:
SelectedValue
is returning anull
value whenSelectedItem
is alsonull
. YourParentFileId
property is an integer (I guess) which doesn't supportnull
values, and it has no way to know how you'd want to convert fromnull
to an integer value. So the Binding throws an error, and the value remains unchanged in your data.You need to specify how you want to convert those null values with a simple Converter like this:
Add it as resource to your view:
And then use it in your
SelectedValue
Binding: