0

I have a listbox and a modelview , which I used to bind listbox items from a obervable collection.

My requirement is that I need to set the selectedItem as well as selectedIndex from view model, so the selected item can be visible to the user.

Hope somebody have solution for me

Manoj AP
  • 11
  • 6

1 Answers1

0

Make a SelectedItem property in your view model after that you can write something like this

SelectedItem="{Binding SelectedItem,UpdateSourceTrigger=PropertyChanged}"

in your XAML.

Arif Mucahid
  • 46
  • 1
  • 6
  • I want to this code make `var charles = new Person() { FirstName = "Charles", LastName = "Darwin" }; viewModel.SelectedPerson = charles;` changes to the list – Manoj AP Aug 07 '20 at 12:41
  • and this is the seletectedPerson property from my view class `public Person SelectedPerson { get { return m_SelectedPerson; } set => SetProperty(ref m_SelectedPerson, value); }` – Manoj AP Aug 07 '20 at 12:45
  • in my xaml I have ` ` – Manoj AP Aug 07 '20 at 12:46
  • If you want to change it after your viewmodel loaded to your window you should implement INotifyPropertyChanged to your view model. – Arif Mucahid Aug 07 '20 at 12:48
  • the selected item already working , I want it reflected on the list [ get selected - in UI] – Manoj AP Aug 07 '20 at 12:49
  • I do implement this `public abstract class ViewModelBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected bool SetProperty(ref T field, T newValue, [CallerMemberName]string propertyName = null) { if (!EqualityComparer.Default.Equals(field, newValue)) { field = newValue; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); return true; } return false; } }` – Manoj AP Aug 07 '20 at 12:50
  • [INotify Implementation](https://stackoverflow.com/questions/36970912/how-do-i-correctly-implement-inotifypropertychanged-for-my-bool-property-and-bin) Can you look at this, I didn't see any mistake in your code but try to debug it, maybe the program isn't invoking the event. – Arif Mucahid Aug 07 '20 at 12:56
  • actually this code working `var pi=viewModel.Persons.Where((p, b) => p.FirstName.Equals(charles.FirstName)); var p1 = (Person) pi.SingleOrDefault(); viewModel.SelectedPerson = p1;` – Manoj AP Aug 07 '20 at 13:07
  • but it is not the purpose – Manoj AP Aug 07 '20 at 13:08