DataTemplate使用MVVM生成菜单 [英] DataTemplate to generate Menu with MVVM
问题描述
我正在尝试使用DataTemplate从我的ViewModels中创建关于MVVM的菜单.基本上,我已经创建了几个类,这些类将存储有关Menu结构的信息.然后,我想使用DataTemplate将菜单结构实现为WPF菜单.
I'm trying to use a DataTemplate to create a Menu from my ViewModels with respect to MVVM. Basically, I've created several classes which will store information about my Menu structure. I then want to realize that menu stucture as a WPF Menu using a DataTemplate.
我有一个菜单服务,该菜单服务允许不同的组件在菜单中注册新菜单和新项目.这是我组织菜单信息(ViewModel)的方式
I have a menu service which allows different components to register new menus and items within the menus. Here's how I've organized my menu information (ViewModel)
我有以下课程: MainMenuViewModel-包含一个TopLevelMenuViewModelCollection(顶级菜单的集合)
I have the following classes: MainMenuViewModel - Contains a TopLevelMenuViewModelCollection (a collection of top level menus)
TopLevelMenuViewModel-包含一个MenuItemGroupViewModelCollection(一组菜单项的集合)以及菜单文本"的名称
TopLevelMenuViewModel - Contains a MenuItemGroupViewModelCollection (a collection of groups of menu items), and a name for the menu 'Text'
MenuItemGroupViewModel-包含一个MenuItemViewModelCollection(菜单项的集合)
MenuItemGroupViewModel - Contains a MenuItemViewModelCollection (collection of menu items)
MenuItemViewModel-包含文本,图像uri,命令,子项MenuItemViewModels
MenuItemViewModel - Contains text, image uri, command, children MenuItemViewModels
我要做的是将DataTemplate应用于以前的类,以将它们转换为普通菜单.
MainMenuViewModel->菜单
MainMenuViewModel -> Menu
TopLevelMenuViewModel->带有标头设置的MenuItems
TopLevelMenuViewModel -> MenuItems with header set
MenuItemGroupViewModel->分隔符,然后是每个MenuItemViewModel的MenuItem
MenuItemGroupViewModel -> Separator followed by a MenuItem for each MenuItemViewModel
MenuItemViewModel-> MenuItem(HeirarchicalDataTemplate)
MenuItemViewModel -> MenuItem (HeirarchicalDataTemplate)
问题是我看不到如何为MenuItemGroupViewModel生成多个MenuItem.. Menu模板希望始终为作为MenuItem的每个项目创建一个ItemContainer.因此,我要么将我的MenuItems放在一个MenuItem中,但显然不起作用,或者根本不起作用.我已经尝试了几件事,但仍然无法弄清楚如何使单个项目产生多个MenuItem.
The problem is I don't see how to generate multiple MenuItems for the MenuItemGroupViewModel. The Menu template wants to always create an ItemContainer for each item which is a MenuItem. Therefore, I either end up with my MenuItems inside a MenuItem which obviously doesn't work, or it doesn't work at all. I've tried several things and still cannot figure out how to make a single item produce more than one MenuItem.
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:--">
<!-- These data templates provide the views for the menu -->
<!-- MenuItemGroupView -->
<Style x:Key="MenuItemGroupStyle" TargetType="{x:Type MenuItem}">
<Setter Property="Header" Value="qqq" />
<!-- Now what? I don't want 1 item here..
I wanted this to start with a <separator /> and list the MenuItemGroupViewModel.MenuItems -->
</Style>
<!-- TopLevelMenuView -->
<Style x:Key="TopLevelMenuStyle" TargetType="{x:Type MenuItem}">
<Setter Property="Header" Value="{Binding Text}" />
<Setter Property="ItemsSource" Value="{Binding MenuGroups}" />
<Setter Property="ItemContainerStyle" Value="{StaticResource MenuItemGroupStyle}"/>
</Style>
<!-- MainMenuView -->
<DataTemplate DataType="{x:Type local:MainMenuViewModel}">
<Menu ItemsSource="{Binding TopLevelMenus}" ItemContainerStyle="{StaticResource TopLevelMenuStyle}" />
</DataTemplate>
<!-- MenuItemView -->
<!--<HierarchicalDataTemplate DataType="{x:Type local:MenuItemViewModel}"
ItemsSource="{Binding Path=Children}"
>
<HierarchicalDataTemplate.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Command"
Value="{Binding Command}" />
</Style>
</HierarchicalDataTemplate.ItemContainerStyle>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding ImageSource}" />
<TextBlock Text="{Binding Text}" />
</StackPanel>
</HierarchicalDataTemplate>-->
请点击链接以更好地了解我正在尝试做的事情
Class Diagram
Basic Menu I want to Make
推荐答案
因为这有点复杂,所以我用一个可下载的示例更新了此答案.
Because this is sort of complicated, I've updated this answer with a downloadable example.
我的目标是允许不同的模块注册菜单命令,并将它们与标题分组在一起,并按适当的顺序对菜单项进行排序.首先,让我们展示菜单的示例.
My goal was to allow different modules to register menu commands and group them together with a title and sort the menu items in a proper order. First of all, let's show an example of what the menu looks like.
这很有用,例如,工具"菜单可以具有模块1"组,其中列出了属于模块1的每个工具的菜单项,模块1可以独立于其他模块注册.
This is useful, for example a "Tools" menu could have a "Module1" group that has menu items listed for each tool that belongs to Module1 which Module1 can register independently of the other modules.
我有一个菜单服务",它允许模块注册新菜单和菜单项.每个节点都有一个Path属性,该属性通知服务将菜单放置在何处.该接口可能在基础架构项目中,因此所有模块都可以解决它.
I have a "menu service" which allows modules to register new menus and menu items. Each node has a Path property which informs the service where to place the menu. This interface is likely in the infrastructure project, so that all modules can resolve it.
public interface IMenuService
{
void AddTopLevelMenu(MenuItemNode node);
void RegisterMenu(MenuItemNode node);
}
然后我可以在适当的地方实现该MenuService. (基础设施项目,单独的模块,也许是外壳).我继续添加一些在整个应用程序范围内定义的默认"菜单,尽管任何模块都可以添加新的顶级菜单.
I can then implement that MenuService wherever is appropriate. (Infrastructure project, Separate Module, maybe the Shell). I go ahead and add some "default" menus that are defined application wide, although any module can add new top level menus.
本来可以用代码创建这些菜单,但是我将它们从资源中拉出了,因为在XAML中将它们写到资源文件中比较容易.我正在将该资源文件添加到我的应用程序资源中,但是您可以直接加载它.
I could have created these menus in code, but I instead pulled them out of the resources because it was easier to write them out in XAML in a resource file. I'm adding that resource file to my application resources, but you could load it directly.
public class MainMenuService : IMenuService
{
MainMenuNode menu;
MenuItemNode fileMenu;
MenuItemNode toolMenu;
MenuItemNode windowMenu;
MenuItemNode helpMenu;
public MainMenuService(MainMenuNode menu)
{
this.menu = menu;
fileMenu = (MenuItemNode)Application.Current.Resources["FileMenu"];
toolMenu = (MenuItemNode)Application.Current.Resources["ToolMenu"];
windowMenu = (MenuItemNode)Application.Current.Resources["WindowMenu"];
helpMenu = (MenuItemNode)Application.Current.Resources["HelpMenu"];
menu.Menus.Add(fileMenu);
menu.Menus.Add(toolMenu);
menu.Menus.Add(windowMenu);
menu.Menus.Add(helpMenu);
}
#region IMenuService Members
public void AddTopLevelMenu(MenuItemNode node)
{
menu.Menus.Add(node);
}
public void RegisterMenu(MenuItemNode node)
{
String[] tokens = node.Path.Split('/');
RegisterMenu(tokens.GetEnumerator(), menu.Menus, node);
}
#endregion
private void RegisterMenu(IEnumerator tokenEnumerator, MenuItemNodeCollection current, MenuItemNode item)
{
if (!tokenEnumerator.MoveNext())
{
current.Add(item);
}
else
{
MenuItemNode menuPath = current.FirstOrDefault(x=> x.Text == tokenEnumerator.Current.ToString());
if (menuPath == null)
{
menuPath = new MenuItemNode(String.Empty);
menuPath.Text = tokenEnumerator.Current.ToString();
current.Add(menuPath);
}
RegisterMenu(tokenEnumerator, menuPath.Children, item);
}
}
}
这是我的资源文件中这些预定义菜单之一的示例:
Here's an example of one of those pre-defined menus in my resource file:
<!-- File Menu Groups -->
<menu:MenuGroupDescription x:Key="fileCommands"
Name="Files"
SortIndex="10" />
<menu:MenuGroupDescription x:Key="printerCommands"
Name="Printing"
SortIndex="90" />
<menu:MenuGroupDescription x:Key="applicationCommands"
Name="Application"
SortIndex="100" />
<menu:MenuItemNode x:Key="FileMenu"
x:Name="FileMenu"
Text="{x:Static inf:DefaultTopLevelMenuNames.File}"
SortIndex="10">
<menu:MenuItemNode Group="{StaticResource fileCommands}"
Text="_Open File..."
SortIndex="10"
Command="{x:Static local:FileCommands.OpenFileCommand}" />
<menu:MenuItemNode Group="{StaticResource fileCommands}" Text="Recent _Files" SortIndex="20"/>
<menu:MenuItemNode Group="{StaticResource fileCommands}" Text="Con_vert..." SortIndex="30"/>
<menu:MenuItemNode Group="{StaticResource fileCommands}"
Text="_Export"
SortIndex="40"
Command="{x:Static local:FileCommands.ExportCommand}" />
<menu:MenuItemNode Group="{StaticResource fileCommands}" Text="_Save" SortIndex="50"/>
<menu:MenuItemNode Group="{StaticResource fileCommands}" Text="Save _All" SortIndex="60"/>
<menu:MenuItemNode Group="{StaticResource fileCommands}"
Text="_Close"
SortIndex="70"
Command="{x:Static local:FileCommands.CloseCommand}" />
<menu:MenuItemNode Group="{StaticResource printerCommands}" Text="Page _Setup..." SortIndex="10"/>
<menu:MenuItemNode Group="{StaticResource printerCommands}" Text="_Print..." SortIndex="10"/>
<menu:MenuItemNode Group="{StaticResource applicationCommands}"
Text="E_xit"
SortIndex="10"
Command="{x:Static local:FileCommands.ExitApplicationCommand}" />
</menu:MenuItemNode>
好的,这里列出了定义我的菜单系统结构的类型...(不是它的样子)
OK, here lists the types that define the structure of my menu system... (Not what it looks like)
MainMenuNode基本存在,因此您可以轻松为其创建另一个模板.您可能是菜单栏或代表菜单整体的东西.
The MainMenuNode basically exists so that you can easily create a different template for it. You probably what a menu bar or something that represents the menu as a whole.
public class MainMenuNode
{
public MainMenuNode()
{
Menus = new MenuItemNodeCollection();
}
public MenuItemNodeCollection Menus { get; private set; }
}
这是每个MenuItem的定义.它们包括一个告诉服务放置位置的路径,一个类似于TabIndex的SortIndex(可让它们以正确的顺序进行组织)以及一个GroupDescription(可让您将它们放入组"中),这些组"可以采用不同的样式并排序.
Here's the definition for each MenuItem. They include a Path which tells the service where to put them, a SortIndex which is sort of like TabIndex that allows them to be organized in the proper order, and a GroupDescription which allows you to put them into "groups" which can be styled differently and sorted.
[ContentProperty("Children")]
public class MenuItemNode : NotificationObject
{
private string text;
private ICommand command;
private Uri imageSource;
private int sortIndex;
public MenuItemNode()
{
Children = new MenuItemNodeCollection();
SortIndex = 50;
}
public MenuItemNode(String path)
{
Children = new MenuItemNodeCollection();
SortIndex = 50;
Path = path;
}
public MenuItemNodeCollection Children { get; private set; }
public ICommand Command
{
get
{
return command;
}
set
{
if (command != value)
{
command = value;
RaisePropertyChanged(() => this.Command);
}
}
}
public Uri ImageSource
{
get
{
return imageSource;
}
set
{
if (imageSource != value)
{
imageSource = value;
RaisePropertyChanged(() => this.ImageSource);
}
}
}
public string Text
{
get
{
return text;
}
set
{
if (text != value)
{
text = value;
RaisePropertyChanged(() => this.Text);
}
}
}
private MenuGroupDescription group;
public MenuGroupDescription Group
{
get { return group; }
set
{
if (group != value)
{
group = value;
RaisePropertyChanged(() => this.Group);
}
}
}
public int SortIndex
{
get
{
return sortIndex;
}
set
{
if (sortIndex != value)
{
sortIndex = value;
RaisePropertyChanged(() => this.SortIndex);
}
}
}
public string Path
{
get;
private set;
}
以及菜单项的集合:
public class MenuItemNodeCollection : ObservableCollection<MenuItemNode>
{
public MenuItemNodeCollection() { }
public MenuItemNodeCollection(IEnumerable<MenuItemNode> items) : base(items) { }
}
这是我最终对MenuItems进行分组的方式.每个人都有一个GroupDescription
Here's how I ended up grouping MenuItems.. Each one has a GroupDescription
public class MenuGroupDescription : NotificationObject, IComparable<MenuGroupDescription>, IComparable
{
private int sortIndex;
public int SortIndex
{
get { return sortIndex; }
set
{
if (sortIndex != value)
{
sortIndex = value;
RaisePropertyChanged(() => this.SortIndex);
}
}
}
private String name;
public String Name
{
get { return name; }
set
{
if (name != value)
{
name = value;
RaisePropertyChanged(() => this.Name);
}
}
}
public MenuGroupDescription()
{
Name = String.Empty;
SortIndex = 50;
}
public override string ToString()
{
return Name;
}
#region IComparable<MenuGroupDescription> Members
public int CompareTo(MenuGroupDescription other)
{
return SortIndex.CompareTo(other.SortIndex);
}
#endregion
#region IComparable Members
public int CompareTo(object obj)
{
if(obj is MenuGroupDescription)
return sortIndex.CompareTo((obj as MenuGroupDescription).SortIndex);
return this.GetHashCode().CompareTo(obj.GetHashCode());
}
#endregion
}
然后,我可以使用以下模板设计菜单的外观:
I then can design what my menu looks like with the following templates:
<local:MenuCollectionViewConverter x:Key="GroupViewConverter" />
<!-- The style for the header of a group of menu items -->
<DataTemplate x:Key="GroupHeaderTemplate"
x:Name="GroupHeader">
<Grid x:Name="gridRoot"
Background="#d9e4ec">
<TextBlock Text="{Binding Name}"
Margin="4" />
<Rectangle Stroke="{x:Static SystemColors.MenuBrush}"
VerticalAlignment="Top"
Height="1" />
<Rectangle Stroke="#bbb"
VerticalAlignment="Bottom"
Height="1" />
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Name}"
Value="{x:Null}">
<Setter TargetName="gridRoot"
Property="Visibility"
Value="Collapsed" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
<!-- Binds the MenuItemNode's properties to the generated MenuItem container -->
<Style x:Key="MenuItemStyle"
TargetType="MenuItem">
<Setter Property="Header"
Value="{Binding Text}" />
<Setter Property="Command"
Value="{Binding Command}" />
<Setter Property="GroupStyleSelector"
Value="{x:Static local:MenuGroupStyleSelectorProxy.MenuGroupStyleSelector}" />
</Style>
<Style x:Key="TopMenuItemStyle"
TargetType="MenuItem">
<Setter Property="Header"
Value="{Binding Text}" />
<Setter Property="Command"
Value="{Binding Command}" />
<Setter Property="GroupStyleSelector"
Value="{x:Static local:MenuGroupStyleSelectorProxy.MenuGroupStyleSelector}" />
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Children.Count}"
Value="0">
<Setter Property="Visibility"
Value="Collapsed" />
</DataTrigger>
<DataTrigger Binding="{Binding}"
Value="{x:Null}">
<Setter Property="Visibility"
Value="Collapsed" />
</DataTrigger>
</Style.Triggers>
</Style>
<!-- MainMenuView -->
<DataTemplate DataType="{x:Type menu:MainMenuNode}">
<Menu ItemsSource="{Binding Menus, Converter={StaticResource GroupViewConverter}}"
ItemContainerStyle="{StaticResource TopMenuItemStyle}" />
</DataTemplate>
<!-- MenuItemView -->
<HierarchicalDataTemplate DataType="{x:Type menu:MenuItemNode}"
ItemsSource="{Binding Children, Converter={StaticResource GroupViewConverter}}"
ItemContainerStyle="{StaticResource MenuItemStyle}" />
完成这项工作的关键是弄清楚如何将具有正确排序定义的CollectionView注入和将定义分组到DataTemplate中.这是我的方法:
A key to make this work was figuring out how to inject my CollectionView with proper sorting definitions and grouping definitions into my DataTemplate. This is how I did it:
[ValueConversion(typeof(MenuItemNodeCollection), typeof(IEnumerable))]
public class MenuCollectionViewConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (targetType != typeof(IEnumerable))
throw new NotImplementedException();
CollectionViewSource src = new CollectionViewSource();
src.GroupDescriptions.Add(new PropertyGroupDescription("Group"));
src.SortDescriptions.Add(new SortDescription("Group", ListSortDirection.Ascending));
src.SortDescriptions.Add(new SortDescription("SortIndex", ListSortDirection.Ascending));
src.Source = value as IEnumerable;
return src.View;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value.GetType() != typeof(CollectionViewSource))
throw new NotImplementedException();
return (value as CollectionViewSource).Source;
}
#endregion
}
public static class MenuGroupStyleSelectorProxy
{
public static GroupStyleSelector MenuGroupStyleSelector { get; private set; }
private static GroupStyle Style { get; set; }
static MenuGroupStyleSelectorProxy()
{
MenuGroupStyleSelector = new GroupStyleSelector(SelectGroupStyle);
Style = new GroupStyle()
{
HeaderTemplate = (DataTemplate)Application.Current.Resources["GroupHeaderTemplate"]
};
}
public static GroupStyle SelectGroupStyle(CollectionViewGroup grp, int target)
{
return Style;
}
}
这篇关于DataTemplate使用MVVM生成菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!