如何将组合框值链接到MVVM中的列表框值? [英] How to link combobox values to listbox values in MVVM?

查看:74
本文介绍了如何将组合框值链接到MVVM中的列表框值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有4个值的组合框,对于组合框中的每个值,列表框应该更新它的值。例如,如果我有蔬菜和水果,当我在组合框中选择水果时,列表框应显示所有水果我怎么能用MVVM做到这一点?我试图用linq查询做到这一点,但没有任何运气。有人请向我解释这是否可能,因为不幸的是没有人做过类似的事情。我发现了一些例子接近我想要什么,但没有帮助。



我从数据库中获取数据,我有一个表,其中包含4个值{courseID,courseName,SNTeacher和education }。



这是我第一次使用这个网站所以请不要判断......谢谢!



我的尝试:



RegisterView.xaml.cs

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

            }
        }











这是我的RegisterTeacher.xaml:






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"/>

推荐答案

我假设您有一个用于组合框的集合,一个用于列表框。



在列表框集合项中,添加一个名为IsVisible的属性。



当你的组合框选择改变时,将您的新IsVisible属性设置为true或false,具体取决于该项是否与组合框中选择的内容相关联。



我派生所有MVVM项目来自名为 Notifiable 的基类。此类实现 INotifyPropertyChanged IDataErrorInfo 接口,并包含在WPF视图模型中有用的几个属性。我把它包括在这里以防你可以使用它。如果你想看到它正在使用中,请查看我的 SQLXAgent - Jobs for SQL Express [ ^ ]文章。所有UI都是WPF,我广泛使用我的通知类。



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.

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


这篇关于如何将组合框值链接到MVVM中的列表框值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆