Databyte
Databyte

Reputation: 1481

Binding the Setter Value in a Style to the main model

i want to write a WPF-Application that shows different pages/scenes. So, I have a ViewModel (MainViewModel) that provides a list of scenes (SceneViewModel). Every scene has a name which can be accessed by a property SceneName.

I create the MainViewModel in Window.DataContext:

<Window.DataContext>
    <!-- Declaratively create an instance of the main model -->
    <models:MainViewModel />
</Window.DataContext>

I then want a menu-item that lists all scenes. When one of the menu-items is clicked, the scene should change. Therefor i created an Command in the MainViewMode: ChangeSceneCommand.

In XAML I want to create the menu-list in the following way:

<Menu Grid.Row="0">
    <Menu.Resources>
       <Style x:Key="SetSceneCommandItem" TargetType="{x:Type MenuItem}">
          <Setter Property="Header" Value="{Binding SceneName}"/>
          <Setter Property="Command" Value="{Binding SetSceneCommand}"/> <-- Here is the problem
          <Setter Property="IsChecked" Value="False" />
       </Style>
    </Menu.Resources>
    <MenuItem Header="Scenes" ItemsSource="{Binding Scenes}"   <--  Scenes is a list with scenes^^
    ItemContainerStyle="{StaticResource SetSceneCommandItem}"  /> <-- Here the style is set
</Menu>

The Item-Header binds well but the "SetSceneCommand" can not be found, because wpf tries to find the "SetSceneCommand"-property in the SceneViewModel. How can i say wpf to access the model in the datacontext out of the style?

PS: You may have noticed that SetSceneCommand will need a scene as parameter to work, but I wanted to implement that later.

Upvotes: 2

Views: 1292

Answers (1)

dkozl
dkozl

Reputation: 33384

You can use RelativeSource. If SetSceneCommand is part of the same context used by Menu then it will look like this:

<Setter 
   Property="Command" 
   Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type Menu}}, Path=DataContext.SetSceneCommand}"/>

this tells Binding to go up the visual tree until Menu and take DataContext.SetSceneCommand from there

Upvotes: 4

Related Questions