6

I'm using a ComboBox with a CompositeCollection as follows:

<ComboBox>
    <ComboBox.ItemsSource>
        <CompositeCollection>
            <ComboBoxItem Content="All"></ComboBoxItem>
            <CollectionContainer Collection="{Binding Source={StaticResource AllBitsSource}}" />
        </CompositeCollection>
    </ComboBox.ItemsSource>
</ComboBox>

The data displayed is exactly as expected, only I now want to set the default index/value/item to be that of the ComboBoxItem with content All and am having some problems.

If I set:

<ComboBoxItem Content="All" IsSelected="True"/>

This gets completely ignored.

I also tried doing:

<ComboBox SelectedIndex="0">

And whilst this does select the All value, when I open the drop down list the value that is highlighted is the very last value to have been loaded onto the ComboBox, and not the All value.

How can I fix this so that my ComboBoxItem content stays selected after the databinding?

EDIT:

I have just tried replacing my <CollectionContainer> with another <ComboBoxItem> and it works fine that way, even though they're still inside the <CompositeCollection>.

EDIT2:

Image showing what the problem is:

Image

EDIT3:

Code for the AllBitsSource:

XAML:

<Window.Resources>
    <CollectionViewSource x:Key="AllBitsSource" Source="{Binding Path=AllBits}" />

Code behind:

private readonly ObservableCollection<string> _bits = new ObservableCollection<string>();

private void GetCurrentSettings()
{
    setttings = display.GetDisplaySettings();

    foreach (var mode in setttings)
    {
        var displaySettingInfoArray = mode.GetInfoArray();

        if (_bits.Contains(displaySettingInfoArray[4]) == false)
        {
            _bits.Add(displaySettingInfoArray[4]);
        }
    }
}

public ObservableCollection<string> AllBits
{
    get { return _bits; }
}

GetCurrentSettings() is called on Main()

cogumel0
  • 2,430
  • 5
  • 29
  • 45

1 Answers1

8

Since you're adding to your Collection after the ComboBox is constructed, you may have to dip into the Loaded event and set your SelectedIndex there...

<ComboBox Loaded="ComboBox_Loaded">
    <ComboBox.ItemsSource>
        <CompositeCollection>
            <ComboBoxItem Content="All" />
            <CollectionContainer Collection="{Binding Source={StaticResource AllBitsSource}}" />
        </CompositeCollection>
    </ComboBox.ItemsSource>
</ComboBox>

Code behind:

private void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
    (sender as ComboBox).SelectedIndex = 0;
}
Nick
  • 645
  • 5
  • 11
  • 1
    Definitely does the trick and I'm marking as right answer, though I'd be interested in finding out if there's a way of doing this with only XAML. – cogumel0 Aug 21 '13 at 19:35
  • @cogumel0 Can you use `SelectedItem` instead of `SelectedIndex`? If so, try it and see if it behaves as desired. – Mike Strobel Jan 10 '14 at 21:09