【发布时间】: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 需要一个场景作为参数才能工作,但我想稍后实现。
【问题讨论】: