Just fiddling around with some WP8.1 development + MVVM-Light toolkit and am having trouble trying to figure out how to achieve something..
Basically:
- I have a
View
(let's call itView1
) which has a control (LongListSelector
in this case) that is databound to a Collection of items (let's call themDataItem
) (which is populated by aService
from aViewModel
)
And I want it so:
- When the user taps on a particular item in this control, it passes the item tapped (or a property of this item) to a new
View
(calledView2
), which will either create a newViewModel
forView2
or re-use an existing one (depending on theKey
of the instances inSimpleIoC
, determined by some property in theDataItem
tapped). - This new
ViewModel
then uses the passed property of theDataItem
tapped in its' constructor to fetch data from a differentService
So how can I achieve this? I am thinking of Creating/Registering the new ViewModel
on the SelectionChanged
event of the control, passing it in the Service
and Property
like so:
private void LongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataItem item = e.AddedItems[0] as DataItem;
SimpleIoc.Default.Register(() => new ViewModel2(new Model2Service(), item.Name));
NavigationService.Navigate(new Uri("/View2.xaml", UriKind.Relative));
}
Which works fine for the first DataItem
tapped, but not when a second is tapped.
Note: I couldn't register ViewModel2
in ViewModelLocator
as I couldn't get DataItem
properties passed to the constructor for ViewModel2
, which is why I'm trying to Register it elsewhere.
Not sure if this is abiding by MVVM architecture, I suppose not as this answer states that I shouldn't be handling this in my View
.
So to recap, I want a user to be able to tap on an item in a LongListSelector
which will then navigate the user to a new View
which is bound to a new (or existing) ViewModel
according to a property of the selected item. How can I achieve this?
Any help would be greatly appreciated.