Home > Software engineering >  Iterate through the Combobox with Checkbox as ItemTemplate
Iterate through the Combobox with Checkbox as ItemTemplate

Time:10-12

How to iterate through the ComboBox whose item template contains a CheckBox as shown below:

<ComboBox Name="cboFruitsName" ItemsSource="{Binding StringFruitsType}" Height="25" Width="300"  HorizontalAlignment="Center" VerticalAlignment="Center" Focusable="False"
          IsTextSearchEnabled="True" StaysOpenOnEdit="True" IsReadOnly="True" IsEditable="True" Text="-- Select Alert Name --">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <CheckBox x:Name="chkBox" Width="Auto" Height="23" Content="{Binding}" Checked="chkBox_Checked" Unchecked="chkBox_Unchecked" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

In the view model I definded the StringFruitsType property as shown below:

public List<string> StringFruitsType
{ 
    get
    {
        return LoadStrings();
    }            
}

 private List<string> LoadStrings()
{
    return new List<string> { "Apple",
                              "Orange",
                              "Grapes",
                              "Mango" };
}

How can we iterate through the ComboBox? I am looking for something as shown below:

foreach(var item in cboFruitsName.Items)
{
   Checkbox cb = (CheckBox)item;
   if(cb != null)
   {
      if(cb.Content.ToString() == SelectedFruitName)
      {
        cb.IsChecked = true;
      }
   }
}

CodePudding user response:

If I understand correctly, your goal is to check the currently selected item of the ComboBox only for display purposes. Bind IsChecked to the IsSelected property of the parent ComboBoxItem container.

<ComboBox.ItemTemplate>
   <DataTemplate>
      <CheckBox x:Name="chkBox" Width="Auto" Height="23" Content="{Binding}"
                IsChecked="{Binding IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ComboBoxItem}}}"/>
   </DataTemplate>
</ComboBox.ItemTemplate>
  • Related