XAML 简单的菜单示例?

ecr0jaav  于 2023-03-27  发布在  其他
关注(0)|答案(1)|浏览(158)

在安装了Avalonia Toolkit和Avalonia for VS 2022的Windows 10 21 H2上使用VS 2022。
靶病变;DR:
1.带有Command="{Binding MainWindow.OnOpenCommand}"的MenuItem显示为灰色。

  1. MenuItem myMenu = this.FindControl<MenuItem>("FileOpen");按预期返回myMenu,但Command属性为null
    我哪里做错了?
    我已经创建了一个绝对香草的'Hello World'项目,根据这里的文档使用以下XAML:https://docs.avaloniaui.net/docs/controls/menu .
<Window xmlns="https://github.com/avaloniaui"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
        x:Class="AvaloniaApplication1.MainWindow"
        Title="AvaloniaApplication1">
        <DockPanel VerticalAlignment="Top">
          <Menu DockPanel.Dock="Top">
            <MenuItem Header="_File">
              <MenuItem Name="FileOpen" IsEnabled="True" Header="_Open..." Command="{Binding OpenCommand}" CommandParameter="{Binding ElementName=MainWindow}"/><Separator/>
              <MenuItem Header="_Exit"/>
            </MenuItem>
            <MenuItem Header="_Edit" >
              <MenuItem Header="Copy"/>
              <MenuItem Header="Paste"/>
            </MenuItem>
          </Menu>
        </DockPanel>
</Window>

相关的C#代码是:

using Avalonia.Controls;
using System.Windows.Input;
using System.Reactive;
using System;

namespace AvaloniaApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            // yep, this works. we find the control
            MenuItem myMenu = this.FindControl<MenuItem>("FileOpen");
            // how to wire this up in code ????
            // myMenu.Command = openCommand;
        }
        //
        public bool CanExitCommand()
        {
            return true;
        }
        public void OnExitCommand() 
        {
            int i = 0;
        }
        //
        public bool CanOpenCommand()
        {
            return true;
        }
        public void OnOpenCommand()
        {
            int i = 0;
        }
    }
}
4c8rllxm

4c8rllxm1#

解决方案可以在binding指令中找到。一个简单的方法,因为显然有替代方案,是这样的:Command="{Binding $parent[Window].OnOpenCommand}"
一个完整的工作示例如下:VS2022的https://github.com/g40/AvaloniaMenu

相关问题