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

San*_*tha 0 c# wpf listbox

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

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
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我需要从ListBox. 我如何继续这里,我尝试了下面的代码,它返回空值,

CheckBox chkBox = lstContactList.SelectedItem as CheckBox;
Run Code Online (Sandbox Code Playgroud)

任何建议,

问候桑吉塔

Ωme*_*Man 5

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

例子

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

public class Passage
{
  public string Name { get; set; }
  public bool IsSelected { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在我的 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>
Run Code Online (Sandbox Code Playgroud)

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

在此处输入图片说明

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

 var selecteds = Passages.Where(ps => ps.IsSelected == true);
Run Code Online (Sandbox Code Playgroud)

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

在此处查看我的答案: