Prism: Share ViewModel's property in parent ViewModel
I'm developing WPF Prism application using Unity container. The issue is: I have a ListBox
, each element has开发者_JAVA技巧 it's own ViewModel. In that element I need to select a location from a list of locations. List of locations is the same for all elements. How could I share this list in the parent ViewModel?
On the internet I googled that I may:
Use
RegionContext
. But it's not right way (RegionContext
could serve only one object, but I have not only locations).Use
SharedService
. But, by my opinion, this way is more suitable for real-time data changing.
Is there the right way? Best practice
If your list is always going to be the same, I usually use a Static class
public static class Lists
{
public static List<Location> Locations {get; set;}
static Lists()
{
Lists = DAL.GetLocations();
}
}
Then in my XAML
<ListBox ItemsSource="{Binding Source={x:Static local:Lists.Locations}}"
SelectedItem="{Binding CurrentLocation}" />
Besides Rachels solution you can create a new view model for the list and insert an instance of this view model into your IoC container. Every view model that resolves this list view model via the container will then get a reference to this single instance.
精彩评论