Mike Eason
Mike Eason

Reputation: 9713

How to access App.Current properties in Windows Universal Apps

I am trying to bind to App.Current.XYZ properties in my View, however this doesn't seem to be possible, here's an example of what I have:

sealed partial class App : Application
{
    public MyClassType MyClass { get; private set; }

    ...

And here is the View:

<Page ... 
    DataContext="{Binding MyClass, Source={x:Static Application.Current}}">

So, this isn't possible because x:Static is no longer supported in Windows Universal (or WinRT), so I have tried exposing the application property through a property in the code-behind, like this:

public MyClassType MyClass
{
    get
    {
        return Application.Current.MyClass;
    }
}

This doesn't work either! There is no intellisense for MyClass, it's completely missing. I have also tried App.Current and still no luck.

Any ideas why my property is not visible through Application.Current.? Or if there is any way I can bind to this property directly through XAML?

Upvotes: 0

Views: 2898

Answers (2)

Metalogic
Metalogic

Reputation: 548

You need to cast Application.Current to your type like so:

public MyClassType MyClass
{
    get
    {
        return ((App)Application.Current).MyClass;
    }
}

Upvotes: 4

Ladi
Ladi

Reputation: 1294

Here is something that may work for you:

Create two classes:

public class MyDataProvider
{
    private static readonly MyDataContainer _myDataContainer = new MyDataContainer();

    public MyDataContainer MyDataContainer { get { return _myDataContainer; } }
}

public class MyDataContainer
{
    public MyClassType MyClass { get; private set; }

    ...
}

Then in App.xaml define this static resource:

<resources:MyDataProvider x:Key="MyDataProvider"/>

Now you should be able to use data binding like this in your XAML code:

Attribute="{Binding MyDataContainer.MyClass, Source={StaticResource MyDataProvider}}"

In your case you could tweak the code so that MyDataContainer is actually your app:

public class MyDataProvider
{
    public Application App { get { return Application.Current; } }
}

and write your data binding like this:

Attribute="{Binding App.MyClass, Source={StaticResource MyDataProvider}}"

In general however I would not use the App class as a provider for sources for data binding. For separation of concerns I would use something like I have above with MyDataProvider and MyDataContainer

Upvotes: 2

Related Questions