2

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

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

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

谢谢!

4

1 回答 1

3

我将假设以下内容:

  1. 列表框的 ItemsSource 属性绑定到 ViewModel 中的某个列表(即 VM_List)。
  2. 列表框的 SelectedItem 属性通过 TwoWay 绑定绑定到 ViewModel 中的某个属性(即 VM_SelectedItem)。

如果以上内容不准确,请提供有关您的实施的更多信息。

您的视图模型应该有一些看起来像这样的代码:

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();
    }
}
于 2013-02-02T21:51:56.043 回答