I have a WPF ListBox
bound to a collection via ItemsSource
.
The selected item is bound to a property on the VM in two-way mode.
I want the selected item to be "unselected" on the UI when I assign a value to the model property that doesn't exist in the collection.
Is that possible? If not is there an alternative to clear the selected item?
Keep in mind I'm working in MVVM pattern so I don't have access to the list itself from the code.
Thanks!
I'm going to assume the following:
If the above is not accurate, please give a little bit more information about your implementation.
Your viewmodel should have some code that looks something like this:
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();
}
}