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:
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()
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With