我使用带有ComboBox的CheckBox作为ItemTemplate,并希望迭代所有项,获取它们的选中状态,如果选中为true,则将它们的内容写入字符串。问题是,我正在使用SqlDataReader来填充和绑定数据库中的ComboBox,并且无法找到一种访问items属性的方法。
<ComboBox>
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Click="CheckBox_Click" Content="{Binding}" IsChecked="{Binding Path=IsSelected, Mode=TwoWay}" Tag="{RelativeSource FindAncestor, AncestorType={x:Type ComboBox}}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>我尝试将ComboBox项转换为对它们的click事件的CheckBoxes,方法如下:
private void CheckBox_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < myComboBox.Items.Count; i++)
{
CheckBox cb = (myComboBox.Items[i] as CheckBox);
if (cb.IsChecked == true)
{
myString += "," + myComboBox.SelectedItem.ToString() + "";
}
}
}但是cb总是返回NULL。我猜这是带有IsChecked属性绑定的东西。
我想让它正常工作,但是我不想创建一个对象/类来填充组合框,因为我需要用数据库来填充它。我真的很感谢你的帮助。
发布于 2013-10-14 18:26:42
您可以这样做(我不坚持MVVM模式),这是动态编写的:
public ArrayList List { get; set; }
public MainWindow()
{
InitializeComponent();
SqlDataReader rdr = cmd.ExecuteReader();
List = new ArrayList();
while (rdr.Read()){
List.Add(new Class{ Id = rdr.GetString(0), Value = rdr.GetString(1), IsChecked= rdr.GetString(1) as bool}); //this class will contain the same data schema in your datareader but using properties
}
rdr.Close();
DataContext = List;
}
<ComboBox Name="ComboBox" ItemsSource="{Binding}" >
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Tag="{Binding Id}" Content="{Binding Name}" IsChecked="{Binding IsChecked}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>https://stackoverflow.com/questions/19366040
复制相似问题