如何通过绑定清除列表框选定项目

时间:2013-02-02 15:59:35

标签: wpf mvvm listbox selection itemscontrol

我通过ListBox绑定了一个WPF ItemsSource。 所选项目以双向模式绑定到VM上的属性。 当我将值分配给集合中不存在的模型属性时,我希望在UI上“取消选择”所选项目。

这可能吗?如果没有,是否有清除所选项目的替代方案?

请记住我正在使用MVVM模式,因此我无法从代码中访问列表本身。

谢谢!

1 个答案:

答案 0 :(得分:3)

我将假设以下内容:

  1. 列表框的ItemsSource属性绑定到ViewModel中的某个列表(即VM_List)。
  2. 列表框的SelectedItem属性绑定到ViewModel中的某个属性(即VM_SelectedItem),并带有TwoWay绑定。
  3. 如果上述内容不准确,请提供有关您的实施的更多信息。

    您的viewmodel应该有一些看起来像这样的代码:

    public class VM : INotifyPropertyChanged
    {
        private ObservableCollection<Student> vmlist = new ObservableCollection<Student>();
        private Student vmselecteditem;
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        public VM()
        {
            PropertyChanged = new PropertyChangedEventHandler(VM_PropertyChanged);
        }
    
        private void VM_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
        }
    
        public ObservableCollection<Student> VM_List
        {
            get
            {
                return vmlist;
            }
        }
    
        public Student VM_SelectedItem
        {
            get
            {
                return vmselecteditem;
            }
            set
            {
                vmselecteditem = value;
            }
        }
    
        public void AddNewStudent(Student NewStudent)
        {
            VM_SelectedItem = null;
            PropertyChanged(this, new PropertyChangedEventArgs("VM_SelectedItem"));
            VM_SelectedItem = NewStudent;
            SaveStudent();
            PropertyChanged(this, new PropertyChangedEventArgs("VM_SelectedItem"));
            //The last line is optional, if you want to select the new student just added.
        }
    
        private void SaveStudent()
        {
            //A fake operation to save the student.
            //To stick with MVVM, the save function should be in the model
            //And this function should just call the one in the model.
            BackgroundWorker b = new BackgroundWorker();
            b.DoWork += new DoWorkEventHandler(b_DoWork);
            b.RunWorkerCompleted += new RunWorkerCompletedEventHandler(b_RunWorkerCompleted);
            b.RunWorkerAsync();
        }
    
        private void AddStudentToList()
        {
            VM_List.Add(VM_SelectedItem);
        }
    
        private void b_DoWork(object sender, DoWorkEventArgs e)
        {
            //Simulating a long save operation
            System.Threading.Thread.Sleep(2000);
        }
    
        private void b_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            AddStudentToList();
        }
    }