c# - 访问 WPF 中列表框内的复选框

标签 c# wpf xaml checkbox listbox

我的代码如下。

<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。有人可以帮忙吗?

最佳答案

从你的代码开始,我尝试了类似的事情

                 // 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);


    } 

我的 View 模型代码是

   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”。 希望这有帮助

关于c# - 访问 WPF 中列表框内的复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9662511/

相关文章:

c# - 我如何在 MVC 中实现两个 Controller

c# - Asp.net Mvc 站点内存不足

c# - 在 C# 的 ListBox 中添加 ListBoxItem?

c# - 无法在 CollectionViewGroup 中找到 ToggleButton

c# - MahApps PasswordBox 不显示清除按钮

c# - 在 MS CRM 中从 JScript 调用 c# 程序

c# - 在 WPF 的代码隐藏中更改字体样式

c# - WPF 中的上下文文本编辑器

c# - 我最近开始自己学习 WPF。声明 Name 与 x :Name? 时有什么区别

c# - TextBlock 不更新内容