C# 将样式中的Setter值绑定到主模型
我想编写一个显示不同页面/场景的WPF应用程序。因此,我有一个ViewModel(MainViewModel),它提供了一个场景列表(SceneViewModel)。每个场景都有一个可由属性C# 将样式中的Setter值绑定到主模型,c#,wpf,xaml,mvvm,C#,Wpf,Xaml,Mvvm,我想编写一个显示不同页面/场景的WPF应用程序。因此,我有一个ViewModel(MainViewModel),它提供了一个场景列表(SceneViewModel)。每个场景都有一个可由属性SceneName访问的名称 我在Window.DataContext中创建MainViewModel: <Window.DataContext> <!-- Declaratively create an instance of the main model --> &
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>
你可以用。如果SetSceneCommand
是菜单使用的相同上下文的一部分,则它将如下所示:
<Setter
Property="Command"
Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type Menu}}, Path=DataContext.SetSceneCommand}"/>
这告诉Binding
向上移动可视化树,直到菜单
并从中获取DataContext.SetSceneCommand
,您可以使用。如果SetSceneCommand
是菜单使用的相同上下文的一部分,则它将如下所示:
<Setter
Property="Command"
Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type Menu}}, Path=DataContext.SetSceneCommand}"/>
这告诉Binding
向上移动可视化树,直到菜单
并从那里获取DataContext.SetSceneCommand