Sunday, 4 March 2012

MonoMac - Open File Dialogs

Another common feature of applications are file dialogs. This blog post shows how easy it is to use them in our MonoMac applications.

The NSOpenPanel class is used here, the documentation can be seen on the Apple developer library here NSOpenPanel.

Without further ado, let's get stuck in!

1. Create a new MonoMac Project

As per the Hello OS X tutorial, edit the MainWindow.xib in xcode and add a button and an action called _OpenClick and a label called _Label1 with an outlet:

2. A small bit of coding

Add the handler for the button action to MainWindowController.cs:

partial void _OpenClick(NSObject sender)
        var openPanel = new NSOpenPanel();
        openPanel.ReleasedWhenClosed = true;
        openPanel.Prompt = "Select file";

       var result = openPanel.RunModal();
       if (result == 1)
             _Label1.StringValue = openPanel.Filename;

Now Run the application and test the code - pressing the Open button should invoke the Open File Dialog:

Select a random file and observe the Label being updated:

3 Additional notes

The NSOpenPanel can also be used to specify if it is for selecting just files or directories using these properties:


Also note that the NSSavePanel can be used for saving files.