はじめに
Xamarin.MacのCocoaアプリケーションで、Windowsのコモンダイアログのような標準的パネルを取り扱えます。
Windowsとの対応、および「ファイルを開く」サンプルを記載しています。
対応
対象 | Mac | Win |
---|---|---|
アラート(メッセージボックス)を表示する | NSAlert | MessageBox |
ファイルを開く | NSOpenPanel | OpenFileDialog |
ファイルを保存する | NSSavePanel | SaveFileDialog |
フォントを選択する | NSFontPanel | FontDialog |
色を選択する | NSColorPanel | ColorDialog |
PDFファイルに出力する | NSPDFPanel |
コード例
ViewController.cs
using System;
using AppKit;
using Foundation;
namespace sample
{
public partial class ViewController : NSViewController
{
public ViewController(IntPtr handle) : base(handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
// Do any additional setup after loading the view.
}
public override NSObject RepresentedObject
{
get
{
return base.RepresentedObject;
}
set
{
base.RepresentedObject = value;
// Update the view, if already loaded.
}
}
// ボタンクリックされたら呼び出されるよう Action で紐付け
partial void ButtonClicked(Foundation.NSObject sender)
{
using(var pnl = NSOpenPanel.OpenPanel)
{
pnl.CanChooseFiles = true;
pnl.CanChooseDirectories = false;
if(pnl.RunModal() == 1) // OK : 1, Cancel : 0
{
var path = pnl.Urls[0].Path;
var alert = new NSAlert();
alert.AlertStyle = NSAlertStyle.Informational;
alert.MessageText = "選択されたファイルのパスです";
alert.InformativeText = $"{path}";
alert.RunModal();
}
}
}
}
}
おわりに
Xamarinのおかげで、WindowsのC#(.NET)アプリケーション開発者はmacOSのアプリも容易に開発できるようになりました。嬉しい時代です。