我创建了一个可能的方法来做到这一点的样本。使用SharedViewModel
包含MenuItems
. 被SharedViewModel
注入ShellViewModel
和 eachTabViewModel
中。Menu 控件绑定到MenuItems
.
When a tab's OnActivate
fires the Menu items can be updated by the TabViewModel
.
<HierarchicalDataTemplate DataType="{x:Type viewModels:MenuItemViewModel}"
ItemsSource="{Binding Path=MenuItems}">
<ContentControl cal:View.Model="{Binding}" />
</HierarchicalDataTemplate>
<Menu IsMainMenu="True"
ItemsSource="{Binding SharedViewModel.MenuItems}" />
共享视图模型:
public class SharedViewModel : PropertyChangedBase
{
private List<MenuItemViewModel> _menuItems;
public List<MenuItemViewModel> MenuItems
{
get { return _menuItems; }
set
{
_menuItems = value;
NotifyOfPropertyChange(() => MenuItems);
}
}
}
更新菜单的 TabViewModel 示例:
protected override void OnActivate()
{
base.OnActivate();
SharedViewModel.MenuItems = new List<MenuItemViewModel>
{
new MenuItemViewModel
{
Header = "MainMenuItem1",
MenuItems =
new List<MenuItemViewModel>
{
new MenuItemViewModel {Header = "SubMenuItem1"},
new MenuItemViewModel {Header = "SubMenuItem2"},
}
},
new MenuItemViewModel
{
Header = "MainMenuItem2",
MenuItems =
new List<MenuItemViewModel>
{
new MenuItemViewModel {Header = "SubMenuItem1"},
new MenuItemViewModel {Header = "SubMenuItem2"},
}
}
};
}