Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a combobox with 4 values and for every value in the combobox,the listbox should update it's values.E.g if I have vegetables and fruits,when I select fruits in the combobox,the listbox should display all the fruits on the menu.How can I do that with MVVM?I have tried to do that with linq queries but without any luck.Can someone please explain to me if this is even possible because unfortunately nobody did anything like it.I have found some examples close to what I want,but no help.

I'm taking the data from the database and I have one table which holds 4 values{courseID,courseName,SNTeacher and education}.

It is the first time when I'm using this website so please don't judge...Thank you!

What I have tried:

RegisterView.xaml.cs
public partial class Register : Window
    {
        RegisterTeacherViewModel regTeacher;
        public Register()
        {
            InitializeComponent();
            regTeacher = new RegisterTeacherViewModel();
            this.DataContext = regTeacher;
            cbxCourses.ItemsSource =regTeacher.GetByEducation();
            coursesList.ItemsSource = regTeacher.MergeWithCombobox();
            
           
          
        }
      
     
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Hide();
        }

        private void fullName_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {

        }

        private void cbxCourses_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            regTeacher.CreateCrazy();
        }

RegisterTeacherViewModel.cs:
<pre lang="c#"><pre>   
 private DelegateCommand _showCourse;
        public DelegateCommand showCourse
        {
            get { return _showCourse; }
            set
            {
                if(_showCourse!=value)
                {
                    _showCourse = value;
                    NotifyOnPropertyChange("showCourse");
                }
            }
        }
   public RegisterTeacherViewModel()
        {
            ButtonCommand = new DelegateCommand(SaveTeacher);
            showCourse = new DelegateCommand(CreateCrazy);
        }

private void CreateCrazy(object obj)
        {

            using (DatabaseStudentsEntities1 db = new DatabaseStudentsEntities1())
            {
                try
                {
                    var query = from Cours in db.Courses
                                select new
                                {
                                    Education = Cours.education,
                                    CourseName = Cours.courseName

                                };
                    foreach (var education in query)
                    {
                        if (Education.Any(p => p.education == "ICT Engineering" && p.courseID < 2000))
                        {
                            courseName.ToList();
                        }
                    }
                }
                catch (Exception ex)

                {
                    MessageBox.Show(ex.Message);
                }

            }
        }





This is my RegisterTeacher.xaml:
<pre>  <ComboBox HorizontalAlignment="Left" DataContextChanged="cbxCourses_DataContextChanged" x:Name="cbxCourses" SelectedItem="{Binding Education}" Margin="126,229.2,0,0" Grid.Row="1" VerticalAlignment="Top" DisplayMemberPath="education"  Width="228" Grid.RowSpan="2">

         <!--<StackPanel Orientation="Horizontal">
             <Image Source="https://www.frostburg.edu/fsu/assets/Image/dept/educ/education_sign_resized.jpg" Height="20"></Image>
             <TextBlock Text="Program"></TextBlock>
         </StackPanel-->
         <!-->-->

     </ComboBox>
     <Button Content="Submit"  HorizontalAlignment="Left" Margin="517,98.4,0,0" Grid.Row="2" VerticalAlignment="Top" Width="110" Height="40"/>
     <Button Content="Cancel"  HorizontalAlignment="Left" Margin="361,98.4,0,0" Grid.Row="2" VerticalAlignment="Top" Width="111" Height="40"/>
     <ListBox HorizontalAlignment="Left" Name="coursesList" Height="240"   Margin="418,13.2,0,0" Grid.Row="1" VerticalAlignment="Top" Width="225" Grid.RowSpan="2"  ItemsSource="{Binding CourseName}" IsSynchronizedWithCurrentItem="{Binding Education, Mode=TwoWay}"/>
     <Button Content="Show courses:" Command="{Binding Path=showCourse}" CommandParameter="{Binding ElementName=coursesList}" Click="Button_Click" HorizontalAlignment="Left" Margin="163,61.4,0,0" Grid.Row="2" VerticalAlignment="Top" Width="137" Height="35"/>
Posted
Updated 13-Mar-18 2:51am
v3
Comments
saimanisha 13-Mar-18 6:42am    
see i dont know how to do it exactly but i was juss discussing with you what am gng to say to u will be benificial or not .when u select combobox using binding to a variable .lets say of class model
variable selection

using query fetch data of varibale model(this may be fruits or pet names etc..)
bind fetched data to list ..
add list to itemsource of listview
Daniel Andrei Popescu 13-Mar-18 6:55am    
OK,interesting approach.I will try it now and let you know!
Daniel Andrei Popescu 13-Mar-18 7:05am    
Right now I have tried it,nothing will change.
this is my method:
Cours cr = new Cours();
string query = "";

SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\User\\source\repos\\VIAApp2Demo\\VIAApp2Demo\\DB\\DatabaseStudents.mdf;Integrated Security=True;Connect Timeout=30");

conn.Open();
if (Education.Any(p => p.education == "ICT Engineering" && p.courseID < 2000))
{
query = "Update Courses SET courseName=@courseName and courseID=@courseID ";
SqlCommand cmd = new SqlCommand(query, conn);
SqlParameter Coursename= cmd.Parameters.AddWithValue("@courseName", SqlDbType.NVarChar);
cmd.Parameters["@courseName"].Value = courseName;
if (Coursename==null)
{
Coursename.Value = DBNull.Value;
}
SqlDataReader rd = cmd.ExecuteReader();
try
{
while(rd.Read())
{
using (DatabaseStudentsEntities1 db = new DatabaseStudentsEntities1())
{
courseName = db.Courses.Select(s => new Cours() { courseName = s.courseName }).ToList();
}
cmd.ExecuteNonQuery();
}
rd.Close();
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
#realJSOP 13-Mar-18 7:57am    
I want to answer this question, but not badly enough to setup a test project and work out all the details. :)
Daniel Andrei Popescu 13-Mar-18 8:06am    
Hi,John,if you know where I can find an example for my problem or if you can give me an advice,it will be more than enough.I have tried to find something relevant everywhere over the internet,and the worst part is that I'm new in MVVM and WPF so any help would be appreciated!

1 solution

I'm assuming you have one collection for the combobox, and one for the listbox.

In your listbox collection item, add a property called IsVisible.

When your combobox selection changes, set your new IsVisible property to true or false, depending on whether or not the item is associated with what was selected in the combobox.

I derive all of my MVVM items from a base class called Notifiable. This class implements the INotifyPropertyChanged and IDataErrorInfo interfaces, and contains several properties that are useful in a WPF viewmodel. I've included it here in case you can make use of it. If you want to see it in use, Check out my SQLXAgent - Jobs for SQL Express[^] article. All of the UI is WPF, and I use my Notifiable class extensively.

C#
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace WpfCommon
{
    /// <summary>
    /// Base class for all objects that require notifiablity and data validation
    /// </summary>
    public class Notifiable : INotifyPropertyChanged, IDataErrorInfo
    {
        #region INotifyPropertyChanged

        /// <summary>
        /// Occurs when a property value changes.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Notifies that the property changed, and sets IsModified to true.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        protected void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                if (propertyName != "IsModified")
                {
                    this.IsModified = true;
                }
            }
        }

        #endregion INotifyPropertyChanged

        #region IDataErrorInfo Code

        /// <summary>
        /// Gets an error message indicating what is wrong with this object.
        /// </summary>
        public string Error
        {
            get { return "Error"; }
        }

        /// <summary>
        /// Gets the error message for the property with the given name.
        /// </summary>
        /// <param name="columnName">Name of the column.</param>
        /// <returns>The generated error message (if any).</returns>
        public string this[string columnName]
        {
            get 
            {
                return Validate(columnName);
            }
        }

        /// <summary>
        /// Validates the specified propery.
        /// </summary>
        /// <param name="properyName">Name of the propery.</param>
        /// <returns>Empty string if valid, otherwise, appropriate error message.</returns>
        protected virtual string Validate(string propertyName)
        {
            //Retun error message if there is error, otherwise return empty string
            string validationMsg = string.Empty;
            return validationMsg;
        }

        #endregion IDataErrorInfo Code

        #region Fields

        private bool isModified;
        private bool isSelected;
        private bool isVisible;
        private bool isEnabled;
        private bool isExpanded;
        private bool isNew;
        private bool isClone;
        private bool isDeleted;
        private bool isValid;

        #endregion Fields

        #region Properties

        /// <summary>
        /// Gets or sets a value indicating whether this instance is modified.
        /// </summary>
        public virtual bool IsModified
        {
            get { return this.isModified; }
            set
            {
                if (this.isModified != value)
                {
                    this.isModified = value;
                    this.NotifyPropertyChanged("IsModified");
                }
            }
        }

        /// <summary>
        /// Gets or sets a value indicating whether this instance is selected.
        /// </summary>
        public virtual bool IsSelected
        {
            get { return this.isSelected; }
            set
            {
                if (this.isSelected != value)
                {
                    this.isSelected = value;
                    this.NotifyPropertyChanged("IsSelected");
                }
            }
        }

        /// <summary>
        /// Gets or sets a value indicating whether this instance is selected.
        /// </summary>
        public virtual bool IsExpanded
        {
            get { return this.isExpanded; }
            set
            {
                if (this.isExpanded != value)
                {
                    this.isExpanded = value;
                    this.NotifyPropertyChanged("IsExpanded");
                }
            }
        }

        /// <summary>
        /// Gets or sets a value indicating whether this instance is visible.
        /// </summary>
        public virtual bool IsVisible
        {
            get { return this.isVisible; }
            set
            {
                if (value != this.isVisible)
                {
                    this.isVisible = value;
                    this.NotifyPropertyChanged("IsVisible");
                }
            }
        }

        /// <summary>
        /// Gets or sets a value indicating whether this instance is enabled.
        /// </summary>
        public virtual bool IsEnabled
        {
            get { return this.isEnabled; }
            set
            {
                if (value != this.isEnabled)
                {
                    this.isEnabled = value;
                    this.NotifyPropertyChanged("IsEnabled");
                }
            }
        }

        /// <summary>
        /// Gets or sets a value indicating whether this instance is new.
        /// </summary>
        public virtual bool IsNew
        {
            get { return this.isNew; }
            set
            {
                if (value != this.isNew)
                {
                    this.isNew = value;
                    this.NotifyPropertyChanged("IsNew");
                }
            }
        }

        /// <summary>
        /// Gets or sets a value indicating whether this instance is a clone of an existing object.
        /// </summary>
        public virtual bool IsClone
        {
            get { return this.isClone; }
            set
            {
                if (value != this.isClone)
                {
                    this.isClone = value;
                    this.NotifyPropertyChanged("IsClone");
                }
            }
        }
        /// <summary>
        /// Get/set the flag indicating whether or not this item is marked for delete.
        /// </summary>
        public virtual bool IsDeleted
        {
            get { return this.isDeleted; }
            set
            {
                if (value != this.isDeleted)
                {
                    this.isDeleted = value;
                    this.NotifyPropertyChanged("IsDeleted");
                }
            }
        }

        /// <summary>
        /// Get or set a flag indicating whether or not this item has an error
        /// </summary>
        public virtual bool IsValid
        {
            get { return this.isValid; }
            set
            {
                if (value != this.isValid)
                {
                    this.isValid = value;
                    this.NotifyPropertyChanged("IsValid");
                }
            }
        }

        #endregion Properties

        #region Constructor

        /// <summary>
        /// Initializes a new instance of the <see cref="Notifiable"/> class.
        /// </summary>
        public Notifiable(bool isNew=false)
        {
            this.IsNew      = isNew;
            this.IsModified = false;
            this.IsVisible  = true;
            this.IsEnabled  = true;
            this.isValid    = true;
            this.IsClone    = false;
            this.IsDeleted  = false;
        }

        #endregion Constructor
    }
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900