bolov
bolov

Reputation: 75697

Set DataContext to a property of a StaticResource

I have a Controller class which manages top components:

public class FooViewModel {}

public class Controller
{
    public FooViewModel Foo1ViewModel {get; protected set;} // = new ...;
}

I have a static resource of the Controller:

<Application.Resources>
    <local:Controller x:Key="AppController" />
</Application.Resources>

And I want Windows and UserControls to have as DataContext properties of Controller.

As far as I got is to set the DataContext to the Controller itself (which is not what I want)

<Window.DataContext>
    <StaticResource ResourceKey="AppController" />
</Window.DataContext>

but I cannot set it to a property of it

<Window.DataContext>
    <!-- something like this path: -->
    <!--  AppController.Foo1ViewModel -->
</Window.DataContext>

Upvotes: 0

Views: 830

Answers (2)

Clemens
Clemens

Reputation: 128060

Use a Binding with the Controller instance as Source:

<Window ...
    DataContext="{Binding Foo1ViewModel, Source={StaticResource AppController}}">

Upvotes: 2

mm8
mm8

Reputation: 169200

Use a Binding:

<Window.DataContext>
    <Binding Path="Foo1ViewModel" Source="{StaticResource AppController}" />
</Window.DataContext>

Upvotes: 1

Related Questions