0

Images to help you understand

There is B Window and B ViewModel in UserControl named A. I want to know in A viewmodel when the selectedItem changes in B window.(or raise an event in A viewmodel) What's the best way?

B Window Combobox

<ComboBox Height="30" ItemsSource="{Binding ModelCollection}"
                      DisplayMemberPath="Name"
                      SelectedItem="{Binding Model}"/>

further modified

Thanks for the reply. Please check if this is a good way.

MainViewModel

Children1.OnContentChanged += new Children1.SelectedInfoChanged(Children2.SelectEvent);

Children1

public delegate void SelectedInfoChanged(Info info);
public event SelectedInfoChanged OnContentChanged;

public Info SelectInfo
{
   get { return _selectInfo; }
   set 
       {
          if(SelectInfo != value)

          _selectInfo = value;
          OnContentChanged(_selectInfo);
       }
   }
}

Children2

public void SelectEvent(Info info)
{

}
GeaGal
  • 11
  • 2

1 Answers1

0

What's the best way?

A common solution is to introduce an event aggregator or a messenger in between the publisher and subscriber of an event/message. Then the subscriber and the publisher only know about the event aggregator. They don't know anything about each other which means that they can evolve independently from one another. This in turn leads to loose coupling which is great from a maintenance perspective.

Please refer to this blog post for more information about the concept.

Another similar option is to inject your view models (or other components) with a shared service and communicate between them using this one.

mm8
  • 163,881
  • 10
  • 57
  • 88
  • Thank you for answer. Could you please confirm the edited content? – GeaGal Jun 09 '22 at 01:15
  • The edited content defines an event and creates a strong relationship between `Children1` and `Children2`. This is the opposite of using an event aggregator. – mm8 Jun 09 '22 at 11:29