Reputation: 7028
I am working on WPF application using MVVM and PRISM and stuck in one issue.
I have two different views(View1 and View2) with their respective view-models.
View1 is main View having a list of domain objects and View2 is used to display the properties of domain object. Now I need to pass the object to View2 every time the selection is changed.
I know that we can do it IEventTrigger
but a view model can listen the event only when it is residing in memory.
So here my problem arise. Since the first there is not selected item. The View2 is not rendered. I dont know how to pass the object to the View2 first time via Event.
What can be the possible solution?
Upvotes: 0
Views: 1332
Reputation: 132618
Since you said in a comment that you don't want one ViewModel to refer to the other, you can use PRISM's EventAggregator for this instead
Whenever the selection changes, broadcast a SelectionChangedMessage
from ViewModel1
, and have ViewModel2
subscribe to receive those messages.
If you also need to know the selected item when ViewModel2
is first created, have it broadcast something like a GetCurrentItemMessage
, which ViewModel1
can subscribe to receive and would make it re-broadcast the SelectionChangedMessage
Also if you're new to PRISM's EventAggregator
, I have a static class on my blog that can be used to simplify how the EventAggregator
is used, as I find the default syntax very confusing and hard to understand at first. I use it for most small applications.
Upvotes: 1
Reputation: 6014
If your View1 contains a List which has a SelectedItem property, you could create a SelectedItem-Property in your ViewModel1. The you create a ViewModel2-Property in your ViewModel1.
You bind to it like:
<ListView SelectedItem="{Binding Path=SelectedItem}">
.
.
</ListView>
<my:view2 DataContext="{Binding Path=ViewModel2}"/>
Finally you pass the SelectedItem in the setter of your SelectedItem-Property:
public object SelectedItem
{
get { return _seledtedItem; }
set { _selectedItem = value; ViewModel2.SomeProperty = _selectedItem; OnPropertyChanged("SelectedItem"); }
}
Upvotes: 1