c# - 将样式中的 Setter 值绑定(bind)到主模型

标签 c# wpf xaml mvvm

我想编写一个显示不同页面/场景的 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 绑定(bind)良好,但找不到“SetSceneCommand”,因为 wpf 尝试在 SceneViewModel 中查找“SetSceneCommand”属性。我怎样才能说 wpf 以不符合样式的方式访问数据上下文中的模型?

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

最佳答案

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

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

这告诉 Binding 在可视化树中向上移动,直到 Menu 并从那里获取 DataContext.SetSceneCommand

关于c# - 将样式中的 Setter 值绑定(bind)到主模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21068162/

相关文章:

c# - 在 Asp.net mvc 中维护 View 状态?

c# - 自定义所选(当前)FlyoutItem 的样式

c# - 从一页滑动到另一页

c# - (Windows 10 UWP) 如何将PivotItem 控件中的Header 属性绑定(bind)到Pivot 控件中的自定义HeaderTemplate?

c# - Entity Framework 6 和工作单元……何时何地?是不是很像ado.net中的交易?

c# - 如何用手指滑动沿所有 3 个轴旋转对象?

c# - 如何断言两个列表包含 NUnit 中具有相同公共(public)属性的元素?

c# - 将参数传递给 ViewModel 中的构造函数

c# - 如何从 python 脚本与 C# 暴露的接口(interface)进行通信?

c# - C# WPF项目正确添加样式资源文件