【问题标题】:Binding the Setter Value in a Style to the main model将样式中的 Setter 值绑定到主模型
【发布时间】:2014-01-11 21:33:53
【问题描述】:

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

我在 Window.DataContext 中创建 MainViewModel:

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

然后我想要一个列出所有场景的菜单项。单击其中一个菜单项时,场景应该改变。为此,我在 MainViewMode 中创建了一个命令: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 需要一个场景作为参数才能工作,但我想稍后实现。

【问题讨论】:

    标签: c# wpf xaml mvvm


    【解决方案1】:

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

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

    这告诉Binding 沿着视觉树向上直到Menu 并从那里获取DataContext.SetSceneCommand

    【讨论】:

      猜你喜欢
      • 2013-10-27
      • 1970-01-01
      • 2015-06-13
      • 2012-05-07
      • 1970-01-01
      • 1970-01-01
      • 2014-05-23
      • 2011-11-17
      • 1970-01-01
      相关资源
      最近更新 更多