Reputation: 313
Ive set up a ComboBox
with about 20 ComboBox items
in it. I wanted to be able to limit the number the user can see when they click a check box e.g
if (checkbox1.ischecked)
{
combobox1.items = item 1, item 2 // correct code here
}
been searching the web and MSDN etc and i am not even sure if its possible any pointers in the right direction would be appreciated
Upvotes: 1
Views: 1788
Reputation: 6961
If you don't want to change the collection, you can simply tweak the visibility, so given this xaml
<ComboBox x:Name="itemsBox">
<ComboBox.Items>
<ComboBoxItem x:Name="itemRed" Content="Red"/>
<ComboBoxItem Content="White"/>
<ComboBoxItem x:Name="itemBlue" Content="Blue"/>
</ComboBox.Items>
</ComboBox>
<CheckBox x:Name="checkBox" Click="checkBox_Click"/>
You just need,
private void checkBox_Click(object sender, RoutedEventArgs e)
{
itemBlue.Visibility = checkBox.IsChecked.Value ? Visibility.Collapsed : Visibility.Visible;
itemRed.Visibility = checkBox.IsChecked.Value ? Visibility.Collapsed : Visibility.Visible;
}
However Sheridan's answer will be far more flexible in the long term as filtering the collections is a far better way to go. If you are trying to do anything other than expose/hide a fixed set of items (note mine above are named explicitly) you really should move to ItemsSource
i.e. If you start doing this,
private void checkBox_Click(object sender, RoutedEventArgs e)
{
foreach(var x in new ComboBoxItem[] { ItemBlue, ItemRed /*, etc*/ })
{
x.Visibility = checkBox.IsChecked.Value ? Visibility.Collapsed : Visibility.Visible;
}
}
Then refactor it to an ItemsSource
Upvotes: 1
Reputation: 69959
Basically, you will have to decide which items will be added to suit you, but in this example, I'm just picking the first 5 items:
if (checkBox1.IsChecked)
{
ObservableCollection<YourItemType> filteredCollection = originalItemsSource.Take(5);
comboBox1.ItemsSource = filteredCollection;
}
else comboBox1.ItemsSource = originalItemsSource;
Note also that I am assuming that you have set the ComboBox.ItemsSource
to a collection (the full collection) named originalItemsSource
, which remains full and unaltered.
Upvotes: 4