访问WPF中列表框内的复选框

本文关键字:复选框 列表 WPF 访问 | 更新日期: 2023-09-27 18:27:22

我的代码如下。

<ListBox x:Name="lstBoxMarket"  BorderThickness="0" Height="Auto" HorizontalAlignment="Center"  Width="200" Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2">
    <ListBox.ItemTemplate>
        <HierarchicalDataTemplate>
            <CheckBox IsChecked="{Binding Checked}"  CommandParameter="{Binding MarketId}" Tag="{Binding MarketId}" Content="{Binding Market}"  Foreground="#FF3D66BE" Name="chkMarket"/>
        </HierarchicalDataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

我想在单击保存按钮时访问列表中选中和取消选中的复选框。我无法立即访问chkMarket。有人能帮忙吗?

访问WPF中列表框内的复选框

从你的代码开始,我尝试了类似的东西

                 // find all T in the VisualTree
                 public static IEnumerable<T> FindVisualChildren<T>(DependencyObject parent) 
        where T : DependencyObject
    {
        List<T> foundChilds = new List<T>();
        int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < childrenCount; i++)
        {
            var child = VisualTreeHelper.GetChild(parent, i);
            T childType = child as T;
            if (childType == null)
            {
                foreach(var other in FindVisualChildren<T>(child))
                    yield return other;
            }
            else
            {
                yield return (T)child;
            }
        }
    }

然后在您的主窗口中

    private void button1_Click(object sender, RoutedEventArgs e)
    {
                           // find all checkboxes in my window
        IEnumerable<CheckBox> myBoxes = FindVisualChildren<CheckBox>(this);
        int numChecked = 0;
        foreach(CheckBox cb in myBoxes)
        {
            if(cb.Name != "chkMarket")
                continue;

            if (cb.IsChecked == true)
                numChecked++;
        }
        MessageBox.Show("Checked items = " + numChecked);

    } 

我的视图模型代码是

   public class ViewModel
{
    public ViewModel()
    {
        _persons = new ObservableCollection<Person>();
        _persons.Add(new Person() { Name = "Paul", Checked = false });
        _persons.Add(new Person() { Name = "Brian", Checked = true });
    }
    private ObservableCollection<Person> _persons;
    public ObservableCollection<Person> Persons
    {
        get { return _persons; }
    }
}
public class Person
{
    public String Name { get; set; }
    public Boolean Checked { get; set; }
}

您应该能够看到消息"Checked items=1"。希望这能帮助

由于是双向绑定,我可以从列表框的项目源访问复选框选择的值。DataTable lstBoxMarketItemSourceDT=((DataView)lstBoxMarket.ItemsSource).ToTable();

检索到的数据表中的"已选中"列提供更新的复选框值。