我想编写一个显示不同页面/场景的 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
。如果 SetSceneCommand
是 Menu
使用的同一上下文的一部分,那么它将如下所示:
<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/