combobox中动态加入几个checkbox,实现下拉框多选,将一个checkbox选中时其内容就会在combobox中显示出来,将另一个checkbox选中时其内容会跟在第一个checkbox的内容后面一起在combobox中显示出来。
前台代码:
<ComboBox Height="23" Name="cmbText" Width="120" IsReadOnly="False" >
<CheckBox Name="chk1" Content="aaaa" Checked="chk1_Checked"/>
<CheckBox Name="chk2" Content="bbbb" Checked="chk1_Checked"/>
<CheckBox Name="chk3" Content="cccc" Checked="chk1_Checked"/>
<CheckBox Name="chk4" Content="dddd" Checked="chk1_Checked"/>
</ComboBox>
后台代码:
StringBuilder sb = new StringBuilder();
//选中的值就添加到下拉框的选择状态。
private void chk1_Checked(object sender, RoutedEventArgs e)
{
CheckBox chk = (CheckBox)sender;
sb.Append(chk.Content.ToString());
cmbText.Text = string.Empty;
cmbText.Items.Insert(cmbText.Items.Count, new ComboBoxItem() { Content = sb.ToString() });
cmbText.Text = sb.ToString();
foreach (var item in cmbText.Items)
{
if (item is CheckBox)
{
CheckBox chks = item as CheckBox;
chks.Visibility = Visibility.Visible;
}
else
{
ComboBoxItem c = item as ComboBoxItem;
c.Visibility = Visibility.Hidden;
}
}
}
有一些细节需要优化。