user7157732
user7157732

Reputation: 347

Get selected items from checkbox in a list - C# WPF

I built a simple view model that populates an observable collection and displays list in the form of checkbox. I would like to get the list of items that are "checked" and of course to be removed from the list if unchecked. Debugging shows the object being selected but how do I send this information to a list for further usage?

public class CheckBoxListItem
{
    public bool Checked { get; set; }
    public string Text { get; set; }
}

ObservableCollection<CheckBoxListItem> monthlyResults =
    new ObservableCollection<CheckBoxListItem>();

public ObservableCollection<CheckBoxListItem> MonthlyResults
{
     get { return monthlyResults; }
     set
     {
         monthlyResults = value;
         base.OnPropertyChanged("StringList");
     }
}

Dictionary<int, CheckBoxListItem> ResultsDict = new Dictionary<int, CheckBoxListItem>();
public List<string> outputlist = new List<string>();
public List<bool> outputyesnolist = new List<bool>();


outputlist.Add("Canon");
outputlist.Add("Sony");
outputlist.Add("Nikon");
outputyesnolist.Add(false);
outputyesnolist.Add(false);
outputyesnolist.Add(false);

for (int j = 0; j < outputlist.Count; j++)
{
    CheckBoxListItem list1 = new CheckBoxListItem();
    list1.Text = outputlist[j];
    list1.Checked = outputyesnolist[j];
    ResultsDict[j] = list1;
}

foreach (var value in ResultsDict.Values)
{
    model.MonthlyResults.Add(value);
}

XAML is defined as:

<ListBox x:Name="Listitems"  Grid.Column="2" SelectionMode="Multiple" ItemsSource="{Binding MonthlyResults}" >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding Text}"
                      IsChecked="{Binding Checked ,Mode=TwoWay}"
                      Click="CheckBox_Click"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Click section for the Checkbox_Click as

private void CheckBox_Click(object sender, RoutedEventArgs e)
{
    var cb = sender as CheckBox;
    var item = cb.DataContext;
    Listitems.SelectedItem = item;
}

Upvotes: 0

Views: 6213

Answers (2)

user7157732
user7157732

Reputation: 347

Thanks to Andy. I modified his answer as

var checkedItems1 = MonthlyResults.Where(B => B.Checked == true);

And to access components:

foreach(var obj in checkedItems1)
 {
    var hello = obj.Text;
 }

Upvotes: 1

Andy
Andy

Reputation: 30428

Assuming all of the bindings are set up correctly, you should be able to search for all of the checked items by looking at the items in MonthlyResults:

var checkedItems = MonthlyResults.Select(item => item.Checked);

Then checkedItems will only contains the items that are checked.

You will need to add using System.Linq; to the top of the source file if it isn't there already for this to compile.

Upvotes: 2

Related Questions