【问题标题】:Iterate through ComboBox items when using CheckBox as ItemTemplate使用 CheckBox 作为 ItemTemplate 时遍历 ComboBox 项
【发布时间】:2013-10-22 08:40:12
【问题描述】:

我使用带有 CheckBox 作为 ItemTemplate 的 ComboBox,我想遍历所有项目,获取它们的选中状态并将它们的内容写入字符串(如果选中为真)。问题是我正在使用 SqlDataReader 从数据库中填充和绑定 ComboBox,但我找不到访问项目 IsChecked 属性的方法。

<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 项作为 CheckBox 投射到它们的点击事件中:

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 属性绑定有关。

我想让它工作,但我不想创建一个对象/类来填充组合框,因为我需要用数据库填充它。非常感谢任何帮助。

【问题讨论】:

  • 啊,自从我这样做以来已经很久了,但我很确定问题是控制树和逻辑树不同,所以我认为你必须搜索控制。为了让您的生活更轻松,只需使用数据绑定并创建自己的类型,然后将您的类型的属性设置为 true。
  • 不要在 WPF 的过程代码中操作 UI 元素。这就是 XAML 的用途。而是在 ViewModel 级别处理此问题。
  • 不要遍历复选框。遍历 Combobox 的 ItemsSource
  • 鞋你能举个例子吗?
  • 投射为 StackPanel。 :)

标签: c# wpf checkbox combobox


【解决方案1】:

你可以做这样的事情(我不坚持 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>

【讨论】:

  • 感谢 Hichem。我没有使用你的代码,但我明白了。我创建了一个用 DataReader 填充的类的列表,然后将该列表绑定到 ComboBox 的 ItemsSource 上。我现在可以遍历 List 并根据需要获取它们的属性。
  • 这正是目的。
猜你喜欢
  • 1970-01-01
  • 2012-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-22
  • 2011-09-18
  • 1970-01-01
相关资源
最近更新 更多