ウィンドウ上部に配置されるメインメニューのサンプルコード
ファイル名:NoXAML23Mainmenu.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UseWPF>true</UseWPF>
</PropertyGroup>
</Project>
ファイル名:App.cs
using System;
using System.Windows;
namespace NoXAML23Mainmenu;
public class App : Application
{
[STAThread]
public static void Main(string[] args)
{
var app = new App();
app.Run();
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var win = new MainWindow();
win.Show();
}
}
ファイル名:AssemblyInfo.cs
using System.Windows;
[assembly:ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
ファイル名:MainWindow.cs
using System.Windows;
using System.Windows.Controls;
namespace NoXAML23Mainmenu;
public class MainWindow : Window
{
public MainWindow()
{
Title = "NoXAML Menu Sample";
Width = 400;
Height = 200;
// メニュー生成
var menu = new Menu();
// 「ファイル」メニュー
var fileMenu = new MenuItem { Header = "_ファイル" };
// 「開く」
var openItem = new MenuItem { Header = "_開く" };
openItem.Click += (s, e) => MessageBox.Show("開くが選択されました");
// 「終了」
var exitItem = new MenuItem { Header = "_終了" };
exitItem.Click += (s, e) => Close();
// サブメニュー追加
fileMenu.Items.Add(openItem);
fileMenu.Items.Add(new Separator());
fileMenu.Items.Add(exitItem);
// メニューにファイルメニュー追加
menu.Items.Add(fileMenu);
// メニューをウィンドウに配置
var dock = new DockPanel();
DockPanel.SetDock(menu, Dock.Top);
dock.Children.Add(menu);
Content = dock;
}
}
コメント