2

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

1 Answer 1

1

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" });
Sign up to request clarification or add additional context in comments.

3 Comments

Well, you would have a ViewModel and commands instead of any code behind. But explaining MVVM is way to broad for a comment or even answer here, there are goods books or turotials written on the subject.
Add MVVM: in this case code will not look much different if you used mvvm. However you will gain some advantages immediatelly: 1. You will get design time support. You can see items in designer and you will see immediatelly if your bindings are correct withour even running your application; 2. Testability of your viewmodels. it's very easy to unit test your app logic if it is separated from views (UI elements); 3. Better readability and maintability. it's much easier to understand what going on in viewmodels, if the code is not mixed with view stuff.
Could you please post a little example for this case, the viewmodel would be a different class that binds the checkboxes for each combobox. Is this correct?

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.