Tarek Saied
Tarek Saied

Reputation: 6616

How to get selected checkboxes items from listbox

I have a listbox where the items contain checkBoxes: I want to get string Content for every CheckBox that user selected

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

Upvotes: 1

Views: 1949

Answers (2)

Charlie
Charlie

Reputation: 1332

You can define a model like this

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

and bind it to the checkbox

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

Then you can get what you want like this

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

Upvotes: 2

Dennis
Dennis

Reputation: 37770

That's why WPF and MVVM are coupled together. Because you can put anything in the ItemsTemplate, to get info about checked items directly from GUI is a pain.

Bind your ListBox to the collection of view models having IsChecked property, than bound that property to CheckBox.IsChecked and you will get checked items from collection.

Upvotes: 0

Related Questions