Get checkbox item from listbox in WPF

2019-09-16 03:21发布

问题:

I am developing WPF application. In which I am adding CheckBoxes to a ListBox in following way.

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
    }
}

Now I need to get the checked items from ListBox. How do I proceed here, I tried below code, which returning null,

CheckBox chkBox = lstContactList.SelectedItem as CheckBox;

Any suggessions,

Regards Sangeetha

回答1:

The way of creating dynamic multiple items in a listbox is not in codebehind, but to create a template for the items, and then bind it to a list of items.

Example

Say I have a bunch of passages List<Passage> Passages { get; set; }:

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

In my xaml I create a template and bind to it

<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>

The result looks like this for my four passages "Alpha", "Beta", "Gamma" and "I-25":

Then if I want the selected item, such as the recently checked Beta above, I just enumerate my List for the selected one(s).

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

Need to list different types objects in one ListBox? Say from binding to a composite collection or an ObservableCollection<T>?

See my answers here:

  • Composite Collection
  • ObservableCollection


标签: c# wpf listbox