mardi 24 janvier 2017

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




Aucun commentaire:

Enregistrer un commentaire