将样式中的Setter值绑定到主模型

时间:2014-01-11 21:33:53

标签: c# wpf xaml mvvm

我想编写一个显示不同页面/场景的WPF应用程序。所以,我有一个ViewModel(MainViewModel),它提供了一个场景列表(SceneViewModel)。每个场景都有一个名称,可以通过属性SceneName访问。

我在Window.DataContext中创建了MainViewModel:

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

然后我想要一个列出所有场景的菜单项。单击其中一个菜单项时,场景应该更改。因此我在MainViewMode中创建了一个Command:ChangeSceneCommand。

在XAML中,我想以下列方式创建菜单列表:

<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>

Item-Header绑定良好但无法找到“SetSceneCommand”,因为wpf试图在SceneViewModel中找到“SetSceneCommand”属性。我怎么能说wpf在样式中访问datacontext中的模型?

PS:您可能已经注意到SetSceneCommand需要一个场景作为参数才能工作,但我想稍后实现它。

1 个答案:

答案 0 :(得分:4)

您可以使用RelativeSource。如果SetSceneCommandMenu使用的相同上下文的一部分,那么它将如下所示:

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

这会让Binding向上看到Menu的可视树,然后从那里取DataContext.SetSceneCommand