0

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;

Thoughts?

4
  • 4
    This is not the way you should use WPF. Read about DataBinding and MVVM or you make anything more complicated than required. Commented Jul 29, 2015 at 17:14
  • 1
    Delete all that and use proper XAML and DataBinding. Commented Jul 29, 2015 at 17:25
  • I managed to get using below code, foreach (ListBoxItem item in lstContactList.Items) { var stackPanel = item.Content as StackPanel; var checkBox = stackPanel.Children[0] as CheckBox; Commented Jul 29, 2015 at 17:41
  • 1
    When creating your text box, add an event handler to its checked changed event. In that handler the sender will cast to a checkbox and you can use that to manage a collection of checked items. This is a pointer not an answer because mvvm will make this far simpler and you look at that. Code behind can be faster to prove an idea but in your case - go straight for mvvm. Commented Jul 29, 2015 at 18:13

2 Answers 2

5

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

enter image description here

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:

Sign up to request clarification or add additional context in comments.

Comments

0

Thank you for your response, it helped me find an answer to my problem. The only detail I would add is to use 'Window.DataContext' to bind the results to the List.

<Window.DataContext>
    <Binding RelativeSource="{RelativeSource Self}"/>
</Window.DataContext>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.