Avalonia UI
首页支持GitHub 仓库English Doc
  • 👋欢迎
  • 文档
    • ⚡快速开始
      • IDE 支持
        • JetBrains Rider 设置
      • 使用 Avalonia 开发
        • Model-View-ViewModel 模式(MVVM)
        • 控件和布局
        • 数据绑定
        • 图像和动画
      • Windows
      • UserControls
      • 资产
      • 开发者工具
      • 错误和警告日志
      • 未处理的异常
      • 应用生命周期
    • 🔁数据绑定
      • 数据上下文
      • 变化通知
      • 绑定
      • 编译绑定
      • 与控件绑定
      • 转换绑定值
      • 绑定到命令
      • 绑定到任务和可观察对象
      • 使用代码进行绑定
      • 在控件模板中实现绑定
      • 绑定Classes
      • 创建和绑定到附加属性
      • Data Validation
    • 🎨样式
      • 样式
      • 选择器
      • 资源
      • 疑难解答
    • 🧰控件
      • AutoCompleteBox
      • Border
      • Buttons
        • Button
        • RepeatButton
        • RadioButton
        • ToggleButton
        • ButtonSpinner
        • SplitButton
        • ToggleSplitButton
      • Calendar
      • Canvas
      • Carousel
      • CheckBox
      • ComboBox
      • ContentControl
      • ContextMenu
      • Decorator
      • DataGrid
        • DataGridColumns
      • DatePicker
      • DockPanel
      • Expander
      • Flyouts
      • Grid
      • GridSplitter
      • Image
      • ItemsControl
      • ItemsRepeater
      • LayoutTransformControl
      • ListBox
      • MaskedTextBox
      • Menu
      • NativeMenu
      • NumericUpDown
      • Panel
      • ProgressBar
      • RelativePanel
      • ScrollBar
      • ScrollViewer
      • Separator
      • Slider
      • SplitView
      • StackPanel
      • TabControl
      • TabStrip
      • TextBlock
      • TrayIcon
      • TreeDataGrid
        • Creating a Hierarchical TreeDataGrid
        • Creating a Flat TreeDataGrid
        • TreeDataGrid column types
      • TimePicker
      • TextBox
      • ToolTip
      • TreeView
      • TransitioningContentControl
      • UserControl
      • Viewbox
      • Window
      • WrapPanel
    • 📚模板
      • 数据模板
      • 在代码中创建数据模板
      • 实现 IDataTemplate 接口
    • ✏️自定义控件
      • 控件类别
      • 定义属性
    • 🖱️输入
      • 路由事件
      • 剪贴板
      • 鼠标与触控设备
      • 快捷键
    • 🔑动画
      • 关键帧动画
      • 过渡
      • 页面过渡
    • 📐布局
      • 面板概述
      • Alignment、Margin 和 Padding
      • 创建自定义面板
    • 📦发布/分发
      • macOS
  • API 参考
    • 🗒️命名空间
      • Avalonia
      • Avalonia.Animation
        • Avalonia.Animation.Easings
        • Avalonia.Animation.Animators
      • Avalonia.Collections
      • Avalonia.Controls
      • Avalonia.Data
        • Avalonia.Data.Core.Plugins
        • Avalonia.Data.Core
        • Avalonia.Data.Converters
      • Avalonia.Diagnostics
      • Avalonia.Dialogs
  • 指南
    • 🐣基础
      • XAML 介绍
      • Code-behind
      • MVVM 架构
      • 在UI线程上操作
    • 🤿深入
      • 在树莓派上运行你的应用
      • 在树莓派上运行你的应用(使用Raspbian Lite)
      • ReactiveUI
        • 视图激活机制
        • 路由
        • 数据持久化
        • 绑定到 Sorted/Filtered 数据
    • 👩‍💻👩💻 开发人员指南
      • 🏭从源代码中构建 Avalonia
      • Avalonia 与 WPF 和 UWP 之间的比较
      • Debugging Previewer
      • Debugging the XAML compiler
      • macOS 开发
      • Release Process
      • 维护稳定的分支
  • 教程
    • 📋待办事项应用
    • 📻音乐商店应用
    • 🕸️在浏览器中运行
    • 📱为移动设备开发
  • 杂项
    • 👪社区
    • 🖥️WPF 开发者建议
    • 📋正在使用 Avalonia 的项目
    • ❔常见问题
由 GitBook 提供支持
在本页
  • Accelerator Keys
  • Menu Commands
  • Menu Icons
  • Checkboxes
  • Dynamically Creating Menus
  • Reference
  • Source code
  • Related Controls

这有帮助吗?

在GitHub上编辑
  1. 文档
  2. 控件

Menu

The Menu control adds a top-level menu to an application. A Menu is usually placed in a DockPanel in a Window, docked to the top of the window:

<Window xmlns="https://github.com/avaloniaui"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <DockPanel>
        <Menu DockPanel.Dock="Top">
            <MenuItem Header="_File">
                <MenuItem Header="_Open..."/>
                <Separator/>
                <MenuItem Header="_Exit"/>
            </MenuItem>
            <MenuItem Header="_Edit">
                <MenuItem Header="Copy"/>
                <MenuItem Header="Paste"/>
            </MenuItem>
        </Menu>
    </DockPanel>
</Window>

A menu will usually contain a set of nested MenuItems. The first level of MenuItems represent the items that will be displayed horizontally along the menu. The second level of MenuItems represent the menu items that will be dropped down from the top-level and subsequent nested MenuItems represent sub-menus.

The text of the MenuItem is displayed by the Header property; the inner content of the MenuItem is where the sub-items are placed.

Separators are added by including a Separator control or a MenuItem with a header of "-".

Accelerator Keys

An accelerator key is a key on your keyboard that you can press to quickly access a menu. It is also sometimes called a hot key, access key or mnemonic.

If you will press Alt with the example above you will see that some letters are underlined. You can use a combination of Alt + underlined letter to navigate within a menu. In Avalonia to identify the accelerator key, you will need to use _ next character to this character would be an accelerator key.

Menu Commands

<Menu>
    <MenuItem Header="_File">
        <MenuItem Header="_Open..." Command="{Binding OpenCommand}"/>
    </MenuItem>
</Menu>

Menu Icons

A menu icon can be displayed by placing an Image in the Icon property:

    <MenuItem Header="_Open...">
        <MenuItem.Icon>
            <Image Source="resm:MyApp.Assets.Open.png"/>
        </MenuItem.Icon>
    </MenuItem>

Checkboxes

Similarly, a CheckBox can be displayed in the Icon property to make the MenuItem checkable:

    <MenuItem Header="_Open...">
        <MenuItem.Icon>
            <CheckBox BorderThickness="0"
                      IsHitTestVisible="False"
                      Command="{Binding ToggleCommand}">
                Toggle _Me
            </CheckBox>
        </MenuItem.Icon>
    </MenuItem>

Dynamically Creating Menus

public class MainWindowViewModel
{
    public MainWindowViewModel()
    {
        OpenCommand = ReactiveCommand.CreateFromTask(Open);
        SaveCommand = ReactiveCommand.Create(Save);
        OpenRecentCommand = ReactiveCommand.Create<string>(OpenRecent);
    }

    public IReadOnlyList<MenuItemViewModel> MenuItems { get; set; }
    public ReactiveCommand<Unit, Unit> OpenCommand { get; }
    public ReactiveCommand<Unit, Unit> SaveCommand { get; }
    public ReactiveCommand<string, Unit> OpenRecentCommand { get; }

    public async Task Open()
    {
        var dialog = new OpenFileDialog();
        var result = await dialog.ShowAsync();

        if (result != null)
        {
            foreach (var path in result)
            {
                System.Diagnostics.Debug.WriteLine($"Opened: {path}");
            }
        }
    }

    public void Save()
    {
        System.Diagnostics.Debug.WriteLine("Save");
    }

    public void OpenRecent(string path)
    {
        System.Diagnostics.Debug.WriteLine($"Open recent: {path}");
    }
}

And a view model for the menu items

public class MenuItemViewModel
{
    public string Header { get; set; }
    public ICommand Command { get; set; }
    public object CommandParameter { get; set; }
    public IList<MenuItemViewModel> Items { get; set; }
}

Next, you can create your menu structure using the view models. The following code when placed in a Window constructor will create a basic menu structure and assign it to the Window's DataContext.

public MainWindow()
{
    InitializeComponent();

    var vm = new MainWindowViewModel();

    vm.MenuItems = new[]
    {
        new MenuItemViewModel
        {
            Header = "_File",
            Items = new[]
            {
                new MenuItemViewModel { Header = "_Open...", Command = vm.OpenCommand },
                new MenuItemViewModel { Header = "Save", Command = vm.SaveCommand },
                new MenuItemViewModel { Header = "-" },
                new MenuItemViewModel
                {
                    Header = "Recent",
                    Items = new[]
                    {
                        new MenuItemViewModel
                        {
                            Header = "File1.txt",
                            Command = vm.OpenRecentCommand,
                            CommandParameter = @"c:\foo\File1.txt"
                        },
                        new MenuItemViewModel
                        {
                            Header = "File2.txt",
                            Command = vm.OpenRecentCommand,
                            CommandParameter = @"c:\foo\File2.txt"
                        },
                    }
                },
            }
        },
        new MenuItemViewModel
        {
            Header = "_Edit",
            Items = new[]
            {
                new MenuItemViewModel { Header = "_Copy" },
                new MenuItemViewModel { Header = "_Paste" },
            }
        }
    };

    DataContext = vm;
}

Finally assign the bindings to the view model in a Style within the menu:

<Menu Items="{Binding MenuItems}">
    <Menu.Styles>
        <Style Selector="MenuItem">
            <Setter Property="Header" Value="{Binding Header}"/>
            <Setter Property="Items" Value="{Binding Items}"/>
            <Setter Property="Command" Value="{Binding Command}"/>
            <Setter Property="CommandParameter" Value="{Binding CommandParameter}"/>
        </Style>
    </Menu.Styles>
</Menu>

Reference

Source code

Related Controls

上一页MaskedTextBox下一页NativeMenu

最后更新于2年前

这有帮助吗?

Like Button, commands can be to MenuItems. The command will be executed when the menu item is clicked or selected with the keyboard:

See the section for more information on binding to commands.

Menus can also be dynamically created using bindings and s. To do this, you will usually create a view model to represent your Window with a set of commands relating to the menu commands:

🧰
bound
Binding to Commands
DataTemplate
Menu
Menu.cs
Separator