Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF ComboBox with CompositeCollection - SelectedIndex not sticking

Tags:

c#

wpf

xaml

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

like image 484
cogumel0 Avatar asked Aug 21 '13 18:08

cogumel0


1 Answers

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;
}
like image 104
Nick Avatar answered Sep 27 '22 20:09

Nick