1
votes

I have a bound WPF comboBox that has an ItemsSource set to a CompositeCollection. I'm trying this to try and accomodate adding <Select> and <Add New...> selections to precede an ObservableCollection of 'regular' objects. What I can't figure out is how to, in code-behind, select one of these added choices.

This is how I'm building the CompositeCollection:

private CompositeCollection CreateItemsSource(ObservableCollection<T> source)
{
  CompositeCollection cmpc = new CompositeCollection();

  cmpc.Add(new ComboBoxItem { Content = "<Select>" });
  cmpc.Add(new ComboBoxItem { Content = "<Add New...>" });

  var cc1 = new CollectionContainer { Collection = source };
  cmpc.Add(cc1);

  return cmpc;
}

This is what the ComboBox looks like:

<DataTemplate x:Key="LookupComboTemplate">
  <TextBlock Text="{Binding}"/>
</DataTemplate>

  <ComboBox ItemsSource="{Binding SubCategories.ItemsSource}" 
            ItemTemplate="{StaticResource LookupComboTemplate}">
    <ComboBox.SelectedItem>
      <Binding Path="SourceData.SubCategoryObj" Mode="TwoWay"></Binding>
    </ComboBox.SelectedItem>
  </ComboBox>

I've got a situation where SelectedItem SourceData.SubCategoryObj is null (it's an optional property). In this case, I want to manually select and display the <Select> choice. But no matter what I do (setting SelectedIndex is ignored, setting SelectedValue to the ComboBoxItem in the CompositeCollection is ignored) I get a blank ComboBox when it renders.

I'd appreciate any advice on how I can do this.

Thanks! Corey.

1

1 Answers

1
votes

You should be able to fix this with a custom valueconverter for your SelectedItem binding. http://wpftutorial.net/ValueConverters.html should give you some pointers.

I'm not sure if combox wants a simple string or some composite object but you can check that. Something like

public class ComboConverter: IValueConverter
{
    public object Convert(object value, Type targetType,
        object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null)
            return "<Select>";
        return value;
    }

    public object ConvertBack(object value, Type targetType,
        object parameter, System.Globalization.CultureInfo culture)
    {
        if (value.toString().Equals("<Select>")
            return null;
        return value;
    }

should give you the "<Select>" entry if the selected item is null.