Libor Zapletal
Libor Zapletal

Reputation: 14102

How to get reference to App

I am trying to implement MVVM pattern for my Windows Phone application. I have my Views in one project and App.xaml in another project. I added property IsTrial to App.xaml but I can't reach it from View by this code:

if ((Application.Current as App).IsTrial)

Because I didn't reference first project with App class but I can't do that because that would cause a circular dependency. What can I do? How can I access App class? Thanks

Upvotes: 2

Views: 435

Answers (1)

bvs
bvs

Reputation: 109

Create an interface in your Views project:

public interface ISupportTrial
{
   bool IsTrial { get; }
}

Implement the interface in App.xaml.cs:

public class App: Application, ISupportTrial
{
...
}

Change the code where you access the app:

var trialApp = Application.Current as ISupportTrial;
if (trialApp == null)
{
   throw new NotSupportedException("Application.Current should implement ISupportTrial");
}
else if (trialApp.IsTrial)
{
    ...
}
else
{
    ...
}

NOTE: Although this will probably work, I don't think that it's a good practice to access Application.Current. You might want to read some articles about Inversion of Control and Dependency injection.

Upvotes: 2

Related Questions