WPF Combobox when SelectedValue is 0 then the Combobox should not select

897 views Asked by At

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.)

1

There are 1 answers

0
almulo On BEST ANSWER

First, the explanation why this doesn't work out of the box:

SelectedValue is returning a null value when SelectedItem is also null. Your ParentFileId property is an integer (I guess) which doesn't support null values, and it has no way to know how you'd want to convert from null 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:

public class NullToZeroConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value.Equals(0))
            return null;
        else
            return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null)
            return 0;
        else
            return value;
    }
}

Add it as resource to your view:

<Grid ...>
    <Grid.Resources>
        <local:NullToZeroConverter x:Key="nullToZeroConverter" />
        ...
    </Grid.Resources>
    ...
</Grid>

And then use it in your SelectedValue Binding:

<ComboBox x:Name="cboParent" 
          SelectedValuePath="FileID"
          DisplayMemberPath="FileName"
          IsEditable="True"
          ItemsSource="{Binding Files}"
          MaxDropDownHeight="125"
          Validation.Error="cboParent_Error"
          SelectedValue="{Binding Path=SelectedFile.ParentFileID,
                                  Converter={StaticResource nullToZeroConverter}}"
          SelectedItem="{Binding Path=SelectedParentFile, Mode=TwoWay}"
          Height="26"/>