从 WPF 中的列表框中获取复选框项

Get checkbox item from listbox in WPF

我正在开发 WPF 应用程序。我在其中按以下方式将 CheckBoxes 添加到 ListBox

foreach (User ls in lst)
{
     AddContacts(ls, lstContactList);
}

private void AddContacts(User UserData, ListBox lstbox)
{
    try
    {
        var txtMsgConversation = new CheckBox()
        {

                Padding = new Thickness(1),
                IsEnabled = true,
                //IsReadOnly = true,
                Background = Brushes.Transparent,
                Foreground = Brushes.White,
                Width = 180,
                Height = 30,
                VerticalAlignment = VerticalAlignment.Top,
                VerticalContentAlignment = VerticalAlignment.Top,
                Content = UserData.Name, //+ "\n" + UserData.ContactNo,
                Margin = new Thickness(10, 10, 10, 10)
        };

        var SpConversation = new StackPanel() { Orientation = Orientation.Horizontal };

        SpConversation.Children.Add(txtMsgConversation);

        var item = new ListBoxItem()
        {
                Content = SpConversation,
                Uid = UserData.Id.ToString(CultureInfo.InvariantCulture),
                Background = Brushes.Black,
                Foreground = Brushes.White,
                BorderThickness = new Thickness(1),
                BorderBrush = Brushes.Gray
        };


        item.Tag = UserData;

        lstbox.Items.Add(item);
    }
    catch (Exception ex)
    {
        //Need to log Exception
    }
}

现在我需要从 ListBox 获取选中的项目。我如何在这里进行,我尝试了下面的代码,它返回 null,

CheckBox chkBox = lstContactList.SelectedItem as CheckBox;

想法?

在列表框中创建动态多个项目的方法不是在代码隐藏中,而是为项目创建模板,然后将其绑定到项目列表。

例子

假设我有一堆段落List<Passage> Passages { get; set; }:

public class Passage
{
  public string Name { get; set; }
  public bool IsSelected { get; set; }
}

在我的 xaml 中,我创建了一个模板并绑定到它

<ListBox ItemsSource="{Binding Passages}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel  Orientation="Horizontal">
                <CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay}" />
                <TextBlock Text="{Binding Path=Name, StringFormat=Passage: {0}}"
                           Foreground="Blue" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

我的四个段落 "Alpha"、"Beta"、"Gamma" 和 "I-25" 的结果如下所示:

然后如果我想要选择的项目,比如上面最近检查的Beta,我只是为选择的项目枚举我的列表。

 var selecteds = Passages.Where(ps => ps.IsSelected == true);

需要在一个ListBox中列出不同类型的对象?从绑定到复合集合或 ObservableCollection<T> 说起?

在这里查看我的回答: