如何遍历其项模板包含CheckBox
的ComboBox
,如下所示:
<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>
在视图模型中,我定义了StringFruitsType
属性,如下所示:
public List<string> StringFruitsType
{
get
{
return LoadStrings();
}
}
private List<string> LoadStrings()
{
return new List<string> { "Apple",
"Orange",
"Grapes",
"Mango" };
}
我们如何迭代ComboBox
?我正在寻找如下所示的东西:
foreach(var item in cboFruitsName.Items)
{
Checkbox cb = (CheckBox)item;
if(cb != null)
{
if(cb.Content.ToString() == SelectedFruitName)
{
cb.IsChecked = true;
}
}
}
如果我理解正确,您的目标是检查ComboBox
的当前所选项目,仅用于显示目的。将IsChecked
绑定到父ComboBoxItem
容器的IsSelected
属性。
<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>