我正在尝试使用 WPF 实现“Mega Menu”样式菜单。要查看网页设计中的大型菜单示例,请参阅 here 。
到目前为止,我已经尝试通过使用 TextBlocks 作为菜单的最高级别来创建类似的界面,然后使用鼠标悬停事件来显示位于文本 block 下方的附加窗口。这很麻烦且不灵活,将来的更改将需要动态添加/删除 TextBlock。
我考虑过使用 WPF 菜单控件,因为我知道样式可以进行大幅修改,但我还没有看到任何方法可以使用菜单控件使用的分层模型生成多列布局。
有更好的方法吗?我是否必须坚持使用自定义窗口和相对定位?有人能给我举一个已经实现的例子吗?
最佳答案
您可以使用 Popup 控件,而不是使用自定义窗口和定位。您可以使用 StaysOpen=false
设置在用户单击屏幕外时将其关闭。
如果您可以选择单击菜单项而不是悬停,则以下自定义控件将起作用:
[TemplatePart(Name="PART_HoverArea", Type=typeof(FrameworkElement))]
[TemplatePart(Name="PART_Popup", Type=typeof(Popup))]
public class MegaMenuItem : HeaderedContentControl
{
private FrameworkElement hoverArea;
private Popup popup;
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
// Unhook old template
if (hoverArea != null)
{
hoverArea.PreviewMouseUp -= ShowPopupOnMouseDown;
}
hoverArea = null;
popup = null;
if (Template == null)
return;
// Hook up new template
hoverArea = (FrameworkElement)Template.FindName("PART_HoverArea", this);
popup = (Popup)Template.FindName("PART_Popup", this);
if (hoverArea == null || popup == null)
return;
hoverArea.PreviewMouseUp += ShowPopupOnMouseDown;
}
private void ShowPopupOnMouseDown(object sender, MouseEventArgs e)
{
popup.PlacementTarget = hoverArea;
popup.Placement = PlacementMode.Bottom;
popup.StaysOpen = false;
popup.IsOpen = true;
}
}
您需要一个样式来显示它 - 像这样。记下 PART_ 模板部分名称:
<Style TargetType="WpfApplication14:MegaMenuItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="WpfApplication14:MegaMenuItem">
<Grid>
<Border Name="PART_HoverArea" Background="#fb9c3b" BorderBrush="White" BorderThickness="0,0,1,0">
<ContentPresenter Content="{TemplateBinding Header}" />
</Border>
<Popup
Name="PART_Popup"
PlacementTarget="{Binding ElementName=HoverArea}"
>
<Border MinWidth="100" MaxWidth="400" MinHeight="40" MaxHeight="200" Background="#0d81c3">
<ContentPresenter Content="{TemplateBinding Content}" />
</Border>
</Popup>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
菜单的 XAML 将为:
<StackPanel Orientation="Horizontal" VerticalAlignment="Top">
<WpfApplication14:MegaMenuItem Header="Parent 1">
<WrapPanel Margin="5">
<TextBlock Text="Put any content you want here" Margin="5" />
<TextBlock Text="Put any content you want here" Margin="5" />
<TextBlock Text="Put any content you want here" Margin="5" />
</WrapPanel>
</WpfApplication14:MegaMenuItem>
<WpfApplication14:MegaMenuItem Header="Parent 2">
<WrapPanel Margin="5">
<TextBlock Text="Put any content you want here" Margin="5" />
<TextBlock Text="Put any content you want here" Margin="5" />
<TextBlock Text="Put any content you want here" Margin="5" />
</WrapPanel>
</WpfApplication14:MegaMenuItem>
</StackPanel>
使菜单在悬停时显示要困难得多,因为弹出窗口会窃取焦点(您可以显示菜单,但如果它们将鼠标悬停在另一个菜单上,则无法轻松隐藏它)。为此,自定义窗口可能会更好。
关于c# - 如何在WPF中实现 "Mega Menus"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5543545/