【问题标题】:How to get selected checkboxes items from listbox如何从列表框中获取选定的复选框项目
【发布时间】:2012-08-08 11:36:43
【问题描述】:

我有一个列表框,其中的项目包含复选框: 我想为用户选择的每个 CheckBox 获取字符串 Content

            <ListBox Name="SendCodecsNamelistBox"
                     Height="52"
                     Margin="150,128,31,65"
                     ItemsSource="{Binding .}">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <CheckBox Content="{Binding Path=.}" />
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

【问题讨论】:

  • 绑定什么?最好从支持 UI 的数据源中获取所需的信息,而不是直接从 UI 中获取信息。

标签: c# wpf checkbox listbox


【解决方案1】:

你可以这样定义模型

public class Model
{
    public string Content { get; set; }
    public bool IsSelected { get; set; }
}

并将其绑定到复选框

        <ListBox.ItemTemplate>
            <DataTemplate>
                <CheckBox Content="{Binding Path=Content}" IsChecked="{Binding Path=IsSelected, Mode=TwoWay}" />
            </DataTemplate>
        </ListBox.ItemTemplate>

        var data = new List<Model>()
        {
            new Model{ Content = "item1", IsSelected = false},
            new Model{ Content = "item2", IsSelected = false},
            new Model{ Content = "item1", IsSelected = false},
            new Model{ Content = "item3", IsSelected = false}
        };

        SendCodecsNamelistBox.ItemsSource = data;

这样就可以得到你想要的了

var selectedContents = data.Where(i => i.IsSelected)
                           .Select(i => i.Content)
                           .ToList();

【讨论】:

    【解决方案2】:

    这就是 WPF 和 MVVM 耦合在一起的原因。因为您可以在ItemsTemplate 中添加任何内容,所以直接从 GUI 获取有关已检查项目的信息是一件很痛苦的事情。

    将您的ListBox 绑定到具有IsChecked 属性的视图模型集合,然后将该属性绑定到CheckBox.IsChecked,您将从集合中获得选中的项目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-20
      • 2011-09-25
      • 1970-01-01
      • 2011-02-26
      • 1970-01-01
      • 1970-01-01
      • 2017-06-09
      相关资源
      最近更新 更多