“Hello Glade#” from F#
Another bit of spiking, a rather tardy follow up from raw GTK#, starting from the C# example at the Mono Project site, but incorporating the earlier example, so as to build in a clean application exit, for one thing.
In the .glade file, I changed the label size from 38, as in
<widget class="GtkLabel" id="label1"> <property name="width_request">38</property>
to 88, so as to allow the displayed text to be longer.
In VS2008 I added the .glade file by including a new F# script file, but renaming it to gui.glade
, pasting in the XML, and setting its properties to have a Build Action of Embedded Resource. The code looks like:
open System | |
open Gtk | |
open Glade | |
let mutable click_count = 0 | |
type Handler() = class | |
[<Widget>] | |
[<DefaultValue(true)>] | |
val mutable button1 : Button | |
[<Widget>] | |
[<DefaultValue(true)>] | |
val mutable label1 : Label | |
[<Widget>] | |
[<DefaultValue(true)>] | |
val mutable window1 : Window | |
end | |
let OnClick (h : Handler) = | |
//h.label1.Text <- "Mono" -- original example's code | |
click_count <- click_count + 1 | |
// Console.WriteLine("Button Click {0}", click_count) | |
h.label1.Text <- String.Format("Button Click {0}", click_count) | |
let OnDelete (args:DeleteEventArgs) = | |
Application.Quit() | |
args.RetVal <- true | |
[<EntryPoint>] | |
let main a = | |
Application.Init() | |
// Developed with Glade 3.8.3 http://ftp.gnome.org/pub/GNOME/binaries/win32/glade/3.8/glade-3-8-3-installer.exe | |
// Needs libglade project file format | |
let gxml = new Glade.XML (null, "gui.glade", "window1", null) | |
let handler = new Handler() | |
gxml.Autoconnect (handler) | |
handler.button1.Clicked | |
|> Event.add (fun _ -> OnClick handler) | |
handler.window1.DeleteEvent | |
|> Event.add OnDelete | |
handler.window1.ShowAll() | |
Application.Run() | |
0 // needs an int return |
Here the widgets are surfaced via a plain data object, Handler
, and their events are wired up much as before via F#'s first class reactive events, which are much more natural (especially when combining events to one handler is required). The project needs a reference to the glade-sharp assembly, above and beyond the ones already required for pure GTK#
Unfortunately, the need for CLR attributes on members is problematic for IronPython -- the least nasty way to achieve the equivalent of the Handler
class would be to compile some C# on the fly.
Unchanged by version 1.9.9.9, February 2010 CTP.
Unchanged by version 3.1.1, January 2014 (except that Add Existing Item
works better for the .glade file in VS2010 and up).
No comments :
Post a Comment