view ComboBoxUtils.cs @ 9:d0e26a896d72

Re #26: Add GTK# wrapper methods * Add ComboBox class with methods to: * Fill a ComboBox * Set selection to item * Set selection to index
author IBBoard <dev@ibboard.co.uk>
date Sat, 16 Jan 2010 15:10:41 +0000
parents
children 3277cb2ecb71
line wrap: on
line source

// This file (ComboBoxUtils.cs) is a part of the IBBoard.GtkSharp project and is copyright 2010 IBBoard
// 
// The file and the library/program it is in are licensed and distributed, without warranty, under the GNU LGPL license, either version 3 of the License or (at your option) any later version. Please see COPYING for more information and the full license.

using System;
using System.Collections.Generic;
using Gtk;

namespace IBBoard.GtkSharp
{
	public delegate string ObjectToStringRenderingMethod<OBJECT_TYPE>(OBJECT_TYPE obj);
	
	public class ComboBoxUtils
	{
		public static void FillCombo<LIST_TYPE>(ComboBox combo, IList<LIST_TYPE> itemList)
		{
			FillCombo(combo, itemList, delegate(LIST_TYPE obj){return obj.ToString();});
		}
		
		public static void FillCombo<LIST_TYPE>(ComboBox combo, IList<LIST_TYPE> itemList, ObjectToStringRenderingMethod<LIST_TYPE> toStringMethod)
		{
			combo.Clear();
			CellRendererText cell = new CellRendererText();
			combo.PackStart(cell, false);
			combo.AddAttribute(cell, "text", 1);
			ListStore store = new ListStore(typeof(LIST_TYPE), typeof(string));
			combo.Model = store;
		
			foreach (LIST_TYPE item in itemList)
			{
				store.AppendValues(item, toStringMethod(item));
			}
		}
		
		public static void SelectItem(ComboBox combo, object item)
		{
			TreeModel model = combo.Model;
			TreeIter iter;
			model.GetIterFirst(out iter);
			
	   		do
			{
				GLib.Value rowItem = new GLib.Value();
				combo.Model.GetValue (iter, 0, ref rowItem);
				
				if (item.Equals(rowItem))
				{
						combo.SetActiveIter(iter);
						break;
				}
			}
			while (combo.Model.IterNext(ref iter));
		}
		
		public static void SelectIndex(ComboBox combo, int idx)
		{
			Gtk.TreeIter iter;
			combo.Model.IterNthChild(out iter, idx);
			combo.SetActiveIter(iter);
		}
	}
}