edgarmtze
edgarmtze

Reputation: 25048

Button that dynamically inserts checkbox to a checkboxlist in wpf

I have two comboBoxes (m and t) with some items each one. Depending on their combinations I show a list of check Boxes.

To show wanted checkboxes depending on selected items on comboBoxes I use a updateList() method.

To know all items, and selected m and t, I made them global variables

xaml

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>

    <ComboBox
    HorizontalAlignment="Left"
    Margin="93,12,0,0"
    VerticalAlignment="Top"
    Width="120"
    Loaded="ComboBoxModulo_Loaded"
    SelectionChanged="ComboBoxModulo_SelectionChanged"/>

    <ComboBox
    HorizontalAlignment="Left"
    Margin="93,80,0,0"
    VerticalAlignment="Top"
    Width="120"
    Loaded="ComboBoxTipo_Loaded"
    SelectionChanged="ComboBoxTipo_SelectionChanged"/>

    <ListBox ItemsSource="{Binding List}" Margin="318,12,12,22">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <CheckBox IsChecked="{Binding Selected}" Content="{Binding Texto}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

    <Button Margin="318,5,5,5" Padding="3" Content="GET SELECTED INFO"
   Grid.Row="1" Click="Button_Click"/>
    <Label Content="M" Height="28" HorizontalAlignment="Left" Margin="12,12,0,0" Name="labelModulo" VerticalAlignment="Top" />
    <Label Content="T" Height="28" HorizontalAlignment="Left" Margin="12,74,0,0" Name="labelTipo" VerticalAlignment="Top" />
</Grid>

code behind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.ComponentModel;

namespace mt
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        /*public MainWindow()
        {
            InitializeComponent();
        }*/

        public ObservableCollection<BoolStringClass> List { get; set; }
        public string m;
        public string t;

        private void ComboBoxModulo_Loaded(object sender, RoutedEventArgs e)
        {
            List<string> mList = new List<string>();
            mList.Add("m1");
            mList.Add("m2");
            var comboBox = sender as ComboBox;
            comboBox.ItemsSource = mList;
            comboBox.SelectedIndex = 0;
        }
        private void ComboBoxModulo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var comboBox = sender as ComboBox;
            string mSelect = comboBox.SelectedItem as string;
            m = mSelect;
            updateList();
        }

         private void ComboBoxTipo_Loaded(object sender, RoutedEventArgs e)
        {
            List<string> tList = new List<string>();
            tList.Add("t1");
            tList.Add("t2");
            var comboBox = sender as ComboBox;
            comboBox.ItemsSource = tList;
            comboBox.SelectedIndex = 0;            
        }
        private void ComboBoxTipo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var comboBox = sender as ComboBox;
            string tSelect = comboBox.SelectedItem as string;
            t = tSelect;
            updateList();
        }

        void updateList()
        {
            List.Clear();
            if (m == "m1" && t == "t1")
            {
                List.Add(new BoolStringClass { Selected = true, Texto = "m1 t1" });
                List.Add(new BoolStringClass { Selected = true, Texto = "m1 t1" });
            }
            else if (m == "m1" && t == "t2")
            {
                List.Add(new BoolStringClass { Selected = true, Texto = "m1 t2" });
                List.Add(new BoolStringClass { Selected = true, Texto = "m1 t2" });
            }
            else if (m == "m2" && t == "t1")
            {
                List.Add(new BoolStringClass { Selected = true, Texto = "m2 t1" });
                List.Add(new BoolStringClass { Selected = true, Texto = "m2 t1" });
            }
            else if (m == "m2" && t == "t2")
            {
                List.Add(new BoolStringClass { Selected = true, Texto = "m1 t2" });
                List.Add(new BoolStringClass { Selected = true, Texto = "m1 t2" });
            }
            this.DataContext = this;       
        }




        public MainWindow()
        {

            InitializeComponent();
            List = new ObservableCollection<BoolStringClass>();


        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //Get a List<BoolStringClass> that contains all selected items:
            var res = (
                    from item in List
                    where item.Selected == true
                    select item
                ).ToList<BoolStringClass>();

            //Convert all items to a concatenated string:
            var res2 =
                    from item in List
                    select item.Texto + (item.Selected ? " selected." : " NOT selected.");
            MessageBox.Show("title:\r\n\r\n" +
                string.Join("\r\n" + "m: "+m + " t:" + t, new List<string>(res2).ToArray()));
        }

    }

    public class BoolStringClass : INotifyPropertyChanged
    {
        public string Texto { get; set; }

        //Provide change-notification for Selected
        private bool _fIsSelected = false;
        public bool Selected
        {
            get { return _fIsSelected; }
            set
            {
                _fIsSelected = value;
                this.OnPropertyChanged("Selected");
            }
        }

        #region INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string strPropertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(strPropertyName));
        }

        #endregion
    }
}

This results on:

enter image description here

However I would like to include a button at the end of the checkbox list, so when it is clicked it adds other checkbox to the list (maybe asking for the name of checkbox...)

It is not necessary to remember other added checboxes combinations if user decides other m and t combination and then comes back.

I would like something like:

enter image description here

Upvotes: 2

Views: 207

Answers (1)

nvoigt
nvoigt

Reputation: 77304

You should really use the MVVM pattern when using WPF. When your project gets more complex, using WPF like it's Windows Forms will make it only as effective as Windows Forms. And you chose WPF for all the power it has compared to Windows Forms, right? Then use MVVM to have this power available.

As for your button: you already do this. When the button is clicked, just add an item like you already do:

List.Add(new BoolStringClass { Selected = true, Texto = "NEW ENTRY" });

Upvotes: 1

Related Questions