[Gtk-sharp-list] More complete Gtk.Bin program

Miguel de Icaza miguel@ximian.com
14 Jul 2003 22:21:50 -0400


Hey guys,

   Just for the record, this sample implements size negotiation (kind of
broken, since Widge.SizeRequest has the wrong signature, and is the
method we should be using).

   As you can see, in general, using Gtk.Bin is not a good idea if you
only want to write a simple composite widget.  Use Table, a Box or a
Fixed instead.

using System;
using Gtk;
using GtkSharp;

//
// A simple Bin class: a simple container that adds padding.
//
class MyPadder : Bin {
	int pad = 50;
	static GLib.Type type;
	Widget child;
	
	static MyPadder ()
	{
	        //
	        // Register the type on the static constructor, so it is
		// available on the instance constructors
		//
		type = RegisterGType (typeof (MyPadder));
	}
	
	public MyPadder () : base (type)
	{
		// To track our child widget.
		Added += new AddedHandler (MyAdded);

		// Participate in size negotiation
		SizeRequested += new SizeRequestedHandler (OnSizeRequested);
		SizeAllocated += new SizeAllocatedHandler (OnSizeAllocated);
	}

	//
	// Invoked to query our size
	//
	void OnSizeRequested (object o, SizeRequestedArgs args)
	{
		if (child != null){
			int width = args.Requisition.width;
			int height = args.Requisition.height;
			
			child.GetSizeRequest (out width, out height);
			if (width == -1 || height == -1)
				width = height = 80;
			SetSizeRequest (width + pad * 2, height + pad * 2);
		} 
		
	}

	//
	// Invoked to propagate our size
	//
	void OnSizeAllocated (object o, SizeAllocatedArgs args)
	{
		if (child != null){
			Gdk.Rectangle mine = args.Allocation;
			Gdk.Rectangle his = mine;

			his.x += pad;
			his.y += pad;
			his.width -= pad * 2;
			his.height -= pad * 2;
			child.SizeAllocate (his);
		}
	}

	//
	// Public property of the Padding widget
	//
	public int Pad {
		get {
			return pad;
		}

		set {
			pad = value;
			QueueResize ();
		}
	}

	void MyAdded (object o, AddedArgs args)
	{
		child = args.Widget;
	}
}

class Y {
	static void Main ()
	{
		Application.Init ();

		Window w = new Window ("Hello");
		MyPadder x = new MyPadder ();
		x.Pad = 100;
		Button b = new Button ("Hola");
		w.Add (x);
		x.Add (b);

		w.ShowAll ();
		
		Application.Run ();
	}
}
-- 
Miguel de Icaza <miguel@ximian.com>