How to create a two-way reference to the SelectedItem ListView property?

I recently took the MVVM project, started by someone who left the company; This is my first time using WPF, but in appearance it first used WPF and OOP ...

Anyway, I have a ListView in XAML and I have a collection class that currently does not contain the SelectedItem property.

Can someone tell me what code I need to link to associate the SelectedItem ListView with the still unwritten property of the SelectedItem of my collection, and then what code do I need to add the SelectedItem of the collection to the ListView?

Apologies for the question at the homework level, but the code I'm working with is such a nightmare that I still can’t wrap my head around “how to write WPF”? at the same time, like "how do I rewrite this horror of coding as OOP?" so if someone can provide me with sample code, I can work on pasting it into a nightmare ...

+3
source share
2 answers

You can use WPF binding to accomplish your task. Sorry, the code will be in C #, but it shouldn't be hard to understand and adapt in VB.NET;):

Xaml TwoWay, , - .

<ListView SelectedItem="{Binding SelectedItem, Mode=TwoWay}" ItemsSource="{Binding MyObjects}"/>

ViewModel INotifyPropertyChanged, WPF ViewModel.

public class MyViewModel: INotifyPropertyChanged
{
  private MyObj selectedItem;
  public MyObj SelectedItem
  {
    get{return this.selectedItem;}
    set
    {
      if(value!=selectedItem)
      {
        selectedItem = value;
        RaisePropertyChanged("SelectedItem");
      }

    [... your collection....]
    public event PropertyChangedEventHandler PropertyChanged;
    public void RaisePropertyChanged(string propertyName)
    {
      var propertyChanged = this.PropertyChanged;
      if(propertyChanged!=null) 
        propertyChanged(new PropertyChangedEventArgs(propertyName));
    }
+6

Lv.selected item , , .

dim s as List( of MyObj) 
ctype(ListVeiw1.SelectedItem,MyObj).MyProp
0

Source: https://habr.com/ru/post/1768239/


All Articles