我正在尝试在应用程序顶部菜单栏上的某项与WPF界面中某项的右键单击上下文菜单之间建立共享菜单。我已经搜索过aroudn,但是我不知道该如何仅共享菜单项列表。
这是帮助您描述UI的图片:
其工作原理是当选择列表中(如在背景显示)项目,这个菜单变得可以使用。我要这样做,以便当您右键单击列表中的项目时,它也显示相同的菜单。我想避免重复代码,因此我在窗口资源中为MenuItem定义了一个资源:
<MenuItem x:Key="modUtilsMenu">
<MenuItem Header="{Binding SelectedMod.ModName}" IsEnabled="False" FontWeight="Bold" />
<MenuItem Header="{DynamicResource string_Checkforupdates}" Command="{Binding SelectedModCheckForUpdatesCommand}" ToolTip="{DynamicResource string_tooltip_checksForUpdatesToThisMod}" >
<MenuItem.Icon>
<fa:ImageAwesome Style="{StaticResource EnableDisableImageStyle}" Icon="Cloud" Foreground="{DynamicResource {x:Static adonisUi:Brushes.ForegroundBrush}}" Height="16" Width="16"/>
</MenuItem.Icon>
</MenuItem>
<MenuItem Header="{DynamicResource string_RestoremodfromME3Tweaks}" Command="{Binding RestoreModFromME3TweaksCommand}" ToolTip="{DynamicResource string_tooltip_forcesUpdateCheck}" >
<MenuItem.Icon>
<fa:ImageAwesome Style="{StaticResource EnableDisableImageStyle}" Icon="CloudDownload" Foreground="{DynamicResource {x:Static adonisUi:Brushes.ForegroundBrush}}" Height="16" Width="16" RenderOptions.BitmapScalingMode="HighQuality"/>
</MenuItem.Icon>
</MenuItem>
...
然后,将其作为Mod Utils菜单项的子元素添加到界面中:
<MenuItem Header="{DynamicResource string_ModUtils}" Padding="4" IsEnabled="{Binding SelectedMod, Converter={StaticResource NullEnabledConverter}}">
<StaticResource ResourceKey="modUtilsMenu"/>
</MenuItem>
显然,这是行不通的,因为它在资源中定义了第二个MenuItem。
但是,我不确定如何存储菜单项的“列表”以添加为另一个对象的子项,因为MenuItem和ContextMenu的根容器元素不同。这些都是基于命令的菜单项。我的上下文菜单也会遇到相同的问题-如何只共享内容而不共享容器?我需要进行数据绑定吗?
我研究了如何在WPF中的上下文菜单和常规菜单之间共享菜单定义,但这似乎仅适用于单个菜单项。我想我可以为每个人做到这一点,但是我正在寻找是否有办法做到这一点,我只需要在一个地方更新它,而不是三个地方就可以使它工作。
Menu
和ContextMenu
均为type ItemsControl
。您可以这样对待它们,例如绑定到项目模型的集合并指定DataTemplate
。
下面的示例创建MenuItem
as XAML资源的集合。
要允许集合的多个实例,将x:Shared
属性设置为至关重要False
。否则,无论引用多少,菜单都只会在视觉树的一个位置呈现:
<Window>
<Window.Resources>
<x:Array x:Key="SharedMenuItems"
Type="MenuItem"
x:Shared="False">
<MenuItem Header="File">
<MenuItem Header="Save" />
</MenuItem>
<MenuItem Header="Settings" />
</x:Array>
</Window.Resources>
<StackPanel x:Name="RootPanel" viewModels:Item.IsMarkedAsRead="True">
<Menu ItemsSource="{StaticResource SharedMenuItems}" />
<Grid>
<Grid.ContextMenu>
<ContextMenu ItemsSource="{StaticResource SharedMenuItems}" />
</Grid.ContextMenu>
</Grid>
</StackPanel>
</Window>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句