galakt
galakt

Reputation: 1439

Prism5 PopupWindowAction and injection

I looked at part of InteractivityQuickstart official example.

<prism:InteractionRequestTrigger SourceObject="{Binding ItemSelectionRequest, Mode=OneWay}">
        <prism:PopupWindowAction>
            <prism:PopupWindowAction.WindowContent>
                <views:ItemSelectionView />
            </prism:PopupWindowAction.WindowContent>
        </prism:PopupWindowAction>
    </prism:InteractionRequestTrigger>

So, ItemSelectionRequest called less-parametre constructor

public ItemSelectionView()
{
    this.DataContext = new ItemSelectionViewModel();
    InitializeComponent();
}

in code-behind of ItemSelectionView.

Questions: 1) How possible to set DataContext without "new", because

public ItemSelectionView(ItemSelectionViewModel model)

or

[Dependency]
public ItemSelectionViewModel ViewModel
{
    set { this.DataContext = value; }
}

doesn`t work. I need to get some services in ViewModel => i need to call something like this

public ItemSelectionViewModel(IEventAggregator eventAggregator)
{
    _eventAggregator=eventAggregator;
}

Upvotes: 1

Views: 510

Answers (2)

GrantA
GrantA

Reputation: 550

Rather than use the ServiceLocator to set your ViewModel as Brian Lagunas suggests, why not have a parameterless constructor for ViewModel, set the ViewModel directly in your View class (XAML or code-behind), and use the ServiceLocator within the ViewModel itself to get the services (or their interfaces) your ViewModel needs? I suggest this for two reasons:

  • Using the ServiceLocator in the constructor of the View for the popup will give you an error of "ServiceLocationProvider must be set" at design time within the "prism:PopupWindowAction.WindowContent" section. (Though it works fine at runtime.)
  • You've already been forced into a situation where you have to bypass dependency injection in some manner, so why not simplify the code, particularly if you only need access to one service anyway.

So you can do something like this:

public ItemSelectionViewModel()
{
    _eventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>();
}

And if you only need to use the IEventAggregator object once, there's no reason to even assign it to a field. Just use the ServiceLocator call where you need to get the Event Aggregator and remove your explicit constructor entirely.

Upvotes: 0

user5420778
user5420778

Reputation:

If you need a service for your Popup ViewModel, you could get it by using the ServiceLocator.

public ItemSelectionView()
{
    InitializeComponent();
    DataContext = ServiceLocator.Current.GetInstance<ItemSelectionViewModel>();
}

Upvotes: 2

Related Questions