System.Drawing: added email to icon and test file headers
[mono.git] / mcs / class / Managed.Windows.Forms / System.Windows.Forms / ListBox.cs
1 /// Permission is hereby granted, free of charge, to any person obtaining
2 // a copy of this software and associated documentation files (the
3 // "Software"), to deal in the Software without restriction, including
4 // without limitation the rights to use, copy, modify, merge, publish,
5 // distribute, sublicense, and/or sell copies of the Software, and to
6 // permit persons to whom the Software is furnished to do so, subject to
7 // the following conditions:
8 //
9 // The above copyright notice and this permission notice shall be
10 // included in all copies or substantial portions of the Software.
11 //
12 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
13 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
15 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
16 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
17 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
18 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19 //
20 // Copyright (c) 2004-2006 Novell, Inc.
21 //
22 // Authors:
23 //      Jordi Mas i Hernandez, jordi@ximian.com
24 //      Mike Kestner  <mkestner@novell.com>
25 //
26
27 // COMPLETE
28
29 using System;
30 using System.Drawing;
31 using System.Collections;
32 using System.ComponentModel;
33 using System.ComponentModel.Design;
34 using System.ComponentModel.Design.Serialization;
35 using System.Globalization;
36 using System.Reflection;
37 using System.Runtime.InteropServices;
38 using System.Collections.Generic;
39
40 namespace System.Windows.Forms
41 {
42         [DefaultProperty("Items")]
43         [DefaultEvent("SelectedIndexChanged")]
44         [Designer ("System.Windows.Forms.Design.ListBoxDesigner, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.IDesigner")]
45         [DefaultBindingProperty ("SelectedValue")]
46         [ClassInterface (ClassInterfaceType.AutoDispatch)]
47         [ComVisible (true)]
48         public class ListBox : ListControl
49         {
50                 public const int DefaultItemHeight = 13;
51                 public const int NoMatches = -1;
52                 
53                 internal enum ItemNavigation
54                 {
55                         First,
56                         Last,
57                         Next,
58                         Previous,
59                         NextPage,
60                         PreviousPage,
61                         PreviousColumn,
62                         NextColumn
63                 }
64                 
65                 Hashtable item_heights;
66                 private int item_height = -1;
67                 private int column_width = 0;
68                 private int requested_height;
69                 private DrawMode draw_mode = DrawMode.Normal;
70                 private int horizontal_extent = 0;
71                 private bool horizontal_scrollbar = false;
72                 private bool integral_height = true;
73                 private bool multicolumn = false;
74                 private bool scroll_always_visible = false;
75                 private SelectedIndexCollection selected_indices;
76                 private SelectedObjectCollection selected_items;
77                 private SelectionMode selection_mode = SelectionMode.One;
78                 private bool sorted = false;
79                 private bool use_tabstops = true;
80                 private int column_width_internal = 120;
81                 private ImplicitVScrollBar vscrollbar;
82                 private ImplicitHScrollBar hscrollbar;
83                 private int hbar_offset;
84                 private bool suspend_layout;
85                 private bool ctrl_pressed = false;
86                 private bool shift_pressed = false;
87                 private bool explicit_item_height = false;
88                 private int top_index = 0;
89                 private int last_visible_index = 0;
90                 private Rectangle items_area;
91                 private int focused_item = -1;
92                 private ObjectCollection items;
93                 private IntegerCollection custom_tab_offsets;
94                 private Padding padding;
95                 private bool use_custom_tab_offsets;
96
97                 public ListBox ()
98                 {
99                         items = CreateItemCollection ();
100                         selected_indices = new SelectedIndexCollection (this);
101                         selected_items = new SelectedObjectCollection (this);
102
103                         requested_height = bounds.Height;
104                         InternalBorderStyle = BorderStyle.Fixed3D;
105                         BackColor = ThemeEngine.Current.ColorWindow;
106
107                         /* Vertical scrollbar */
108                         vscrollbar = new ImplicitVScrollBar ();
109                         vscrollbar.Minimum = 0;
110                         vscrollbar.SmallChange = 1;
111                         vscrollbar.LargeChange = 1;
112                         vscrollbar.Maximum = 0;
113                         vscrollbar.ValueChanged += new EventHandler (VerticalScrollEvent);
114                         vscrollbar.Visible = false;
115
116                         /* Horizontal scrollbar */
117                         hscrollbar = new ImplicitHScrollBar ();
118                         hscrollbar.Minimum = 0;
119                         hscrollbar.SmallChange = 1;
120                         hscrollbar.LargeChange = 1;
121                         hscrollbar.Maximum = 0;
122                         hscrollbar.Visible = false;
123                         hscrollbar.ValueChanged += new EventHandler (HorizontalScrollEvent);
124
125                         Controls.AddImplicit (vscrollbar);
126                         Controls.AddImplicit (hscrollbar);
127
128                         /* Events */
129                         MouseDown += new MouseEventHandler (OnMouseDownLB);
130                         MouseMove += new MouseEventHandler (OnMouseMoveLB);
131                         MouseUp += new MouseEventHandler (OnMouseUpLB);
132                         MouseWheel += new MouseEventHandler (OnMouseWheelLB);
133                         KeyUp += new KeyEventHandler (OnKeyUpLB);
134                         GotFocus += new EventHandler (OnGotFocus);
135                         LostFocus += new EventHandler (OnLostFocus);
136                         
137                         SetStyle (ControlStyles.UserPaint, false);
138
139                         custom_tab_offsets = new IntegerCollection (this);
140                 }
141
142                 #region Events
143                 static object DrawItemEvent = new object ();
144                 static object MeasureItemEvent = new object ();
145                 static object SelectedIndexChangedEvent = new object ();
146
147                 [Browsable (false)]
148                 [EditorBrowsable (EditorBrowsableState.Never)]
149                 public new event EventHandler BackgroundImageChanged {
150                         add { base.BackgroundImageChanged += value; }
151                         remove { base.BackgroundImageChanged -= value; }
152                 }
153
154                 [Browsable (false)]
155                 [EditorBrowsable (EditorBrowsableState.Never)]
156                 public new event EventHandler BackgroundImageLayoutChanged {
157                         add { base.BackgroundImageLayoutChanged += value; }
158                         remove { base.BackgroundImageLayoutChanged -= value; }
159                 }
160
161                 [Browsable (true)]
162                 [EditorBrowsable (EditorBrowsableState.Always)]
163                 public new event EventHandler Click {
164                         add { base.Click += value; }
165                         remove { base.Click -= value; }
166                 }
167
168                 public event DrawItemEventHandler DrawItem {
169                         add { Events.AddHandler (DrawItemEvent, value); }
170                         remove { Events.RemoveHandler (DrawItemEvent, value); }
171                 }
172
173                 public event MeasureItemEventHandler MeasureItem {
174                         add { Events.AddHandler (MeasureItemEvent, value); }
175                         remove { Events.RemoveHandler (MeasureItemEvent, value); }
176                 }
177
178                 [Browsable (true)]
179                 [EditorBrowsable (EditorBrowsableState.Always)]
180                 public new event MouseEventHandler MouseClick {
181                         add { base.MouseClick += value; }
182                         remove { base.MouseClick -= value; }
183                 }
184
185                 [Browsable (false)]
186                 [EditorBrowsable (EditorBrowsableState.Never)]
187                 public new event EventHandler PaddingChanged {
188                         add { base.PaddingChanged += value; }
189                         remove { base.PaddingChanged -= value; }
190                 }
191
192                 [Browsable (false)]
193                 [EditorBrowsable (EditorBrowsableState.Never)]
194                 public new event PaintEventHandler Paint {
195                         add { base.Paint += value; }
196                         remove { base.Paint -= value; }
197                 }
198
199                 public event EventHandler SelectedIndexChanged {
200                         add { Events.AddHandler (SelectedIndexChangedEvent, value); }
201                         remove { Events.RemoveHandler (SelectedIndexChangedEvent, value); }
202                 }
203
204                 [Browsable (false)]
205                 [EditorBrowsable (EditorBrowsableState.Advanced)]
206                 public new event EventHandler TextChanged {
207                         add { base.TextChanged += value; }
208                         remove { base.TextChanged -= value; }
209                 }
210                 #endregion // Events
211
212                 #region UIA Framework Events 
213                 //NOTE:
214                 //      We are using Reflection to add/remove internal events.
215                 //      Class ListProvider uses the events.
216                 //
217                 //Event used to generate UIA Selection Pattern 
218                 static object UIASelectionModeChangedEvent = new object ();
219
220                 internal event EventHandler UIASelectionModeChanged {
221                         add { Events.AddHandler (UIASelectionModeChangedEvent, value); }
222                         remove { Events.RemoveHandler (UIASelectionModeChangedEvent, value); }
223                 }
224
225                 internal void OnUIASelectionModeChangedEvent ()
226                 {
227                         EventHandler eh = (EventHandler) Events [UIASelectionModeChangedEvent];
228                         if (eh != null)
229                                 eh (this, EventArgs.Empty);
230                 }
231
232                 static object UIAFocusedItemChangedEvent = new object ();
233
234                 internal event EventHandler UIAFocusedItemChanged {
235                         add { Events.AddHandler (UIAFocusedItemChangedEvent, value); }
236                         remove { Events.RemoveHandler (UIAFocusedItemChangedEvent, value); }
237                 }
238
239                 internal void OnUIAFocusedItemChangedEvent ()
240                 {
241                         EventHandler eh = (EventHandler) Events [UIAFocusedItemChangedEvent];
242                         if (eh != null)
243                                 eh (this, EventArgs.Empty);
244                 }
245                 #endregion UIA Framework Events 
246
247                 #region Public Properties
248                 public override Color BackColor {
249                         get { return base.BackColor; }
250                         set {
251                                 if (base.BackColor == value)
252                                         return;
253
254                                 base.BackColor = value;
255                                 base.Refresh ();        // Careful. Calling the base method is not the same that calling 
256                         }                               // the overriden one that refresh also all the items
257                 }
258
259                 [Browsable (false)]
260                 [EditorBrowsable (EditorBrowsableState.Never)]
261                 public override Image BackgroundImage {
262                         get { return base.BackgroundImage; }
263                         set { 
264                                 base.BackgroundImage = value;
265                                 base.Refresh ();
266                         }
267                 }
268
269                 [Browsable (false)]
270                 [EditorBrowsable (EditorBrowsableState.Never)]
271                 public override ImageLayout BackgroundImageLayout {
272                         get { return base.BackgroundImageLayout; }
273                         set { base.BackgroundImageLayout = value; }
274                 }
275
276                 [DefaultValue (BorderStyle.Fixed3D)]
277                 [DispId(-504)]
278                 public BorderStyle BorderStyle {
279                         get { return InternalBorderStyle; }
280                         set { 
281                                 InternalBorderStyle = value; 
282                                 UpdateListBoxBounds ();
283                         }
284                 }
285
286                 [DefaultValue (0)]
287                 [Localizable (true)]
288                 public int ColumnWidth {
289                         get { return column_width; }
290                         set {
291                                 if (value < 0)
292                                         throw new ArgumentException ("A value less than zero is assigned to the property.");
293
294                                 column_width = value;
295
296                                 if (value == 0)
297                                         ColumnWidthInternal = 120;
298                                 else
299                                         ColumnWidthInternal = value;
300
301                                 base.Refresh ();
302                         }
303                 }
304
305                 protected override CreateParams CreateParams {
306                         get { return base.CreateParams;}
307                 }
308
309                 [Browsable (false)]
310                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
311                 public IntegerCollection CustomTabOffsets {
312                         get { return custom_tab_offsets; }
313                 }
314
315                 protected override Size DefaultSize {
316                         get { return new Size (120, 96); }
317                 }
318
319                 [RefreshProperties(RefreshProperties.Repaint)]
320                 [DefaultValue (DrawMode.Normal)]
321                 public virtual DrawMode DrawMode {
322                         get { return draw_mode; }
323                         set {
324                                 if (!Enum.IsDefined (typeof (DrawMode), value))
325                                         throw new InvalidEnumArgumentException (string.Format("Enum argument value '{0}' is not valid for DrawMode", value));
326                                         
327                                 if (value == DrawMode.OwnerDrawVariable && multicolumn == true)
328                                         throw new ArgumentException ("Cannot have variable height and multicolumn");
329
330                                 if (draw_mode == value)
331                                         return;
332
333                                 draw_mode = value;
334
335                                 if (draw_mode == DrawMode.OwnerDrawVariable)
336                                         item_heights = new Hashtable ();
337                                 else
338                                         item_heights = null;
339
340                                 if (Parent != null)
341                                         Parent.PerformLayout (this, "DrawMode");
342                                 base.Refresh ();
343                         }
344                 }
345
346                 public override Font Font {
347                         get { return base.Font; }
348                         set { base.Font = value; }
349                 }
350
351                 public override Color ForeColor {
352                         get { return base.ForeColor; }
353                         set {
354                                 if (base.ForeColor == value)
355                                         return;
356
357                                 base.ForeColor = value;
358                                 base.Refresh ();
359                         }
360                 }
361
362                 [DefaultValue (0)]
363                 [Localizable (true)]
364                 public int HorizontalExtent {
365                         get { return horizontal_extent; }
366                         set {
367                                 if (horizontal_extent == value)
368                                         return;
369
370                                 horizontal_extent = value;
371                                 base.Refresh ();
372                         }
373                 }
374
375                 [DefaultValue (false)]
376                 [Localizable (true)]
377                 public bool HorizontalScrollbar {
378                         get { return horizontal_scrollbar; }
379                         set {
380                                 if (horizontal_scrollbar == value)
381                                         return;
382
383                                 horizontal_scrollbar = value;
384                                 UpdateScrollBars ();
385                                 base.Refresh ();
386                         }
387                 }
388
389                 [DefaultValue (true)]
390                 [Localizable (true)]
391                 [RefreshProperties(RefreshProperties.Repaint)]
392                 public bool IntegralHeight {
393                         get { return integral_height; }
394                         set {
395                                 if (integral_height == value)
396                                         return;
397
398                                 integral_height = value;
399                                 UpdateListBoxBounds ();
400                         }
401                 }
402
403                 [DefaultValue (13)]
404                 [Localizable (true)]
405                 [RefreshProperties(RefreshProperties.Repaint)]
406                 public virtual int ItemHeight {
407                         get {
408                                 if (item_height == -1) {
409                                         SizeF sz = TextRenderer.MeasureString ("The quick brown Fox", Font);
410                                         item_height = (int) sz.Height;
411                                 }
412                                 return item_height;
413                         }
414                         set {
415                                 if (value > 255)
416                                         throw new ArgumentOutOfRangeException ("The ItemHeight property was set beyond 255 pixels");
417
418                                 explicit_item_height = true;
419                                 if (item_height == value)
420                                         return;
421
422                                 item_height = value;
423                                 if (IntegralHeight)
424                                         UpdateListBoxBounds ();
425                                 LayoutListBox ();
426                         }
427                 }
428
429                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
430                 [Localizable (true)]
431                 [Editor ("System.Windows.Forms.Design.ListControlStringCollectionEditor, " + Consts.AssemblySystem_Design, typeof (System.Drawing.Design.UITypeEditor))]
432                 [MergableProperty (false)]
433                 public ObjectCollection Items {
434                         get { return items; }
435                 }
436
437                 [DefaultValue (false)]
438                 public bool MultiColumn {
439                         get { return multicolumn; }
440                         set {
441                                 if (multicolumn == value)
442                                         return;
443
444                                 if (value == true && DrawMode == DrawMode.OwnerDrawVariable)
445                                         throw new ArgumentException ("A multicolumn ListBox cannot have a variable-sized height.");
446                                         
447                                 multicolumn = value;
448                                 LayoutListBox ();
449                                 Invalidate ();
450                         }
451                 }
452
453                 [Browsable (false)]
454                 [EditorBrowsable (EditorBrowsableState.Never)]
455                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
456                 public new Padding Padding {
457                         get { return padding; }
458                         set { padding = value; }
459                 }
460
461                 [Browsable (false)]
462                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
463                 [EditorBrowsable (EditorBrowsableState.Advanced)]
464                 public int PreferredHeight {
465                         get {
466                                 int itemsHeight = 0;
467                                 if (draw_mode == DrawMode.Normal)
468                                         itemsHeight = FontHeight * items.Count;
469                                 else if (draw_mode == DrawMode.OwnerDrawFixed)
470                                         itemsHeight = ItemHeight * items.Count;
471                                 else if (draw_mode == DrawMode.OwnerDrawVariable) {
472                                         for (int i = 0; i < items.Count; i++)
473                                                 itemsHeight += (int) item_heights [Items [i]];
474                                 }
475                                 
476                                 return itemsHeight;
477                         }
478                 }
479
480                 public override RightToLeft RightToLeft {
481                         get { return base.RightToLeft; }
482                         set {
483                                 base.RightToLeft = value;
484                                 if (base.RightToLeft == RightToLeft.Yes)
485                                         StringFormat.Alignment = StringAlignment.Far;
486                                 else
487                                         StringFormat.Alignment = StringAlignment.Near;
488                                 base.Refresh ();
489                         }
490                 }
491
492                 // Only affects the Vertical ScrollBar
493                 [DefaultValue (false)]
494                 [Localizable (true)]
495                 public bool ScrollAlwaysVisible {
496                         get { return scroll_always_visible; }
497                         set {
498                                 if (scroll_always_visible == value)
499                                         return;
500
501                                 scroll_always_visible = value;
502                                 UpdateScrollBars ();
503                         }
504                 }
505
506                 [Bindable(true)]
507                 [Browsable (false)]
508                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
509                 public override int SelectedIndex {
510                         get { 
511                                 if (selected_indices == null)
512                                         return -1;
513                                         
514                                 return selected_indices.Count > 0 ? selected_indices [0] : -1;
515                         }
516                         set {
517                                 if (value < -1 || value >= Items.Count)
518                                         throw new ArgumentOutOfRangeException ("Index of out range");
519
520                                 if (SelectionMode == SelectionMode.None)
521                                         throw new ArgumentException ("cannot call this method if SelectionMode is SelectionMode.None");
522
523                                 if (value == -1)
524                                         selected_indices.Clear ();
525                                 else
526                                         selected_indices.Add (value);
527                         }
528                 }
529
530                 [Browsable (false)]
531                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
532                 public SelectedIndexCollection SelectedIndices {
533                         get { return selected_indices; }
534                 }
535
536                 [Bindable(true)]
537                 [Browsable (false)]
538                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
539                 public object SelectedItem {
540                         get {
541                                 if (SelectedItems.Count > 0)
542                                         return SelectedItems[0];
543                                 else
544                                         return null;
545                         }
546                         set {
547                                 if (value != null && !Items.Contains (value))
548                                         return; // FIXME: this is probably an exception
549                                         
550                                 SelectedIndex = value == null ? - 1 : Items.IndexOf (value);
551                         }
552                 }
553
554                 [Browsable (false)]
555                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
556                 public SelectedObjectCollection SelectedItems {
557                         get {return selected_items;}
558                 }
559
560                 [DefaultValue (SelectionMode.One)]
561                 public virtual SelectionMode SelectionMode {
562                         get { return selection_mode; }
563                         set {
564                                 if (!Enum.IsDefined (typeof (SelectionMode), value))
565                                         throw new InvalidEnumArgumentException (string.Format("Enum argument value '{0}' is not valid for SelectionMode", value));
566
567                                 if (selection_mode == value)
568                                         return;
569                                         
570                                 selection_mode = value;
571                                         
572                                 switch (selection_mode) {
573                                 case SelectionMode.None: 
574                                         SelectedIndices.Clear ();
575                                         break;
576
577                                 case SelectionMode.One:
578                                         // FIXME: Probably this can be improved
579                                         ArrayList old_selection = (ArrayList) SelectedIndices.List.Clone ();
580                                         for (int i = 1; i < old_selection.Count; i++)
581                                                 SelectedIndices.Remove ((int)old_selection [i]);
582                                         break;
583
584                                 default:
585                                         break;
586                                 }
587
588                                 // UIA Framework: Generates SelectionModeChanged event.
589                                 OnUIASelectionModeChangedEvent ();
590                         }
591                 }
592
593                 [DefaultValue (false)]
594                 public bool Sorted {
595                         get { return sorted; }
596                         set {
597                                 if (sorted == value)
598                                         return;
599
600                                 sorted = value;
601                                 if (sorted)
602                                         Sort ();
603                         }
604                 }
605
606                 [Bindable (false)]
607                 [Browsable (false)]
608                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
609                 [EditorBrowsable (EditorBrowsableState.Advanced)]
610                 public override string Text {
611                         get {
612                                 if (SelectionMode != SelectionMode.None && SelectedIndex != -1)
613                                         return GetItemText (SelectedItem);
614
615                                 return base.Text;
616                         }
617                         set {
618
619                                 base.Text = value;
620
621                                 if (SelectionMode == SelectionMode.None)
622                                         return;
623
624                                 int index;
625
626                                 index = FindStringExact (value);
627
628                                 if (index == -1)
629                                         return;
630
631                                 SelectedIndex = index;
632                         }
633                 }
634
635                 [Browsable (false)]
636                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
637                 public int TopIndex {
638                         get { return top_index; }
639                         set {
640                                 if (value == top_index)
641                                         return;
642
643                                 if (value < 0 || value >= Items.Count)
644                                         return;
645
646                                 int page_size = (items_area.Height / ItemHeight);
647                                 
648                                 if (Items.Count < page_size)
649                                         value = 0;
650                                 else if (!multicolumn)
651                                         top_index = Math.Min (value, Items.Count - page_size);
652                                 else
653                                         top_index = value;
654                                         
655                                 UpdateTopItem ();
656                                 base.Refresh ();
657                         }
658                 }
659
660                 [Browsable (false)]
661                 [DefaultValue (false)]
662                 public bool UseCustomTabOffsets {
663                         get { return use_custom_tab_offsets; }
664                         set { 
665                                 if (use_custom_tab_offsets != value) {
666                                         use_custom_tab_offsets = value;
667                                         CalculateTabStops ();
668                                 }
669                          }
670                 }
671
672                 [DefaultValue (true)]
673                 public bool UseTabStops {
674                         get { return use_tabstops; }
675                         set {
676                                 if (use_tabstops == value)
677                                         return;
678
679                                 use_tabstops = value;
680                                 CalculateTabStops ();
681                         }
682                 }
683
684                 protected override bool AllowSelection {
685                         get {
686                                 return SelectionMode != SelectionMode.None;
687                         }
688                 }
689                 #endregion Public Properties
690
691                 #region Private Properties
692
693                 private int ColumnWidthInternal {
694                         get { return column_width_internal; }
695                         set { column_width_internal = value; }
696                 }
697
698                 private int row_count = 1;
699                 private int RowCount {
700                         get {
701                                 return MultiColumn ? row_count : Items.Count;
702                         }
703                 }
704
705                 #endregion Private Properties
706
707                 #region UIA Framework Properties
708
709                 internal ScrollBar UIAHScrollBar {
710                         get { return hscrollbar; }
711                 }
712
713                 internal ScrollBar UIAVScrollBar {
714                         get { return vscrollbar; }
715                 }
716
717                 #endregion UIA Framework Properties
718
719                 #region Public Methods
720                 [Obsolete ("this method has been deprecated")]
721                 protected virtual void AddItemsCore (object[] value)
722                 {
723                         Items.AddRange (value);
724                 }
725
726                 public void BeginUpdate ()
727                 {
728                         suspend_layout = true;
729                 }
730
731                 public void ClearSelected ()
732                 {
733                         selected_indices.Clear ();
734                 }
735
736                 protected virtual ObjectCollection CreateItemCollection ()
737                 {
738                         return new ObjectCollection (this);
739                 }
740
741                 public void EndUpdate ()
742                 {
743                         suspend_layout = false;
744                         LayoutListBox ();
745                         base.Refresh ();
746                 }
747
748                 public int FindString (String s)
749                 {
750                         return FindString (s, -1);
751                 }
752
753                 public int FindString (string s,  int startIndex)
754                 {
755                         if (Items.Count == 0)
756                                 return -1; // No exception throwing if empty
757
758                         if (startIndex < -1 || startIndex >= Items.Count)
759                                 throw new ArgumentOutOfRangeException ("Index of out range");
760
761                         startIndex = (startIndex == Items.Count - 1) ? 0 : startIndex + 1;
762
763                         int i = startIndex;
764                         while (true) {
765                                 string text = GetItemText (Items [i]);
766                                 if (CultureInfo.CurrentCulture.CompareInfo.IsPrefix (text, s,
767                                                 CompareOptions.IgnoreCase))
768                                         return i;
769
770                                 i = (i == Items.Count - 1) ? 0 : i + 1;
771                                 if (i == startIndex)
772                                         break;
773                         }
774
775                         return NoMatches;
776                 }
777
778                 public int FindStringExact (string s)
779                 {
780                         return FindStringExact (s, -1);
781                 }
782
783                 public int FindStringExact (string s,  int startIndex)
784                 {
785                         if (Items.Count == 0)
786                                 return -1; // No exception throwing if empty
787
788                         if (startIndex < -1 || startIndex >= Items.Count)
789                                 throw new ArgumentOutOfRangeException ("Index of out range");
790
791                         startIndex = (startIndex + 1 == Items.Count) ? 0 : startIndex + 1;
792
793                         int i = startIndex;
794                         while (true) {
795                                 if (String.Compare (GetItemText (Items[i]), s, true) == 0)
796                                         return i;
797
798                                 i = (i + 1 == Items.Count) ? 0 : i + 1;
799                                 if (i == startIndex)
800                                         break;
801                         }
802
803                         return NoMatches;
804                 }
805
806                 public int GetItemHeight (int index)
807                 {
808                         if (index < 0 || index >= Items.Count)
809                                 throw new ArgumentOutOfRangeException ("Index of out range");
810                                 
811                         if (DrawMode == DrawMode.OwnerDrawVariable && IsHandleCreated == true) {
812                                 
813                                 object o = Items [index];
814                                 if (item_heights.Contains (o))
815                                         return (int) item_heights [o];
816                                 
817                                 MeasureItemEventArgs args = new MeasureItemEventArgs (DeviceContext, index, ItemHeight);
818                                 OnMeasureItem (args);
819                                 item_heights [o] = args.ItemHeight;
820                                 return args.ItemHeight;
821                         }
822
823                         return ItemHeight;
824                 }
825
826                 public Rectangle GetItemRectangle (int index)
827                 {
828                         if (index < 0 || index >= Items.Count)
829                                 throw new  ArgumentOutOfRangeException ("GetItemRectangle index out of range.");
830
831                         Rectangle rect = new Rectangle ();
832
833                         if (MultiColumn) {
834                                 int col = index / RowCount;
835                                 int y = index;
836                                 if (y < 0) // We convert it to valid positive value 
837                                         y += RowCount * (top_index / RowCount);
838                                 rect.Y = (y % RowCount) * ItemHeight;
839                                 rect.X = (col - (top_index / RowCount)) * ColumnWidthInternal;
840                                 rect.Height = ItemHeight;
841                                 rect.Width = ColumnWidthInternal;
842                         } else {
843                                 rect.X = 0;
844                                 rect.Height = GetItemHeight (index);
845                                 rect.Width = items_area.Width;
846                                 
847                                 if (DrawMode == DrawMode.OwnerDrawVariable) {
848                                         rect.Y = 0;
849                                         if (index >= top_index) {
850                                                 for (int i = top_index; i < index; i++) {
851                                                         rect.Y += GetItemHeight (i);
852                                                 }
853                                         } else {
854                                                 for (int i = index; i < top_index; i++) {
855                                                         rect.Y -= GetItemHeight (i);
856                                                 }
857                                         }
858                                 } else {
859                                         rect.Y = ItemHeight * (index - top_index);      
860                                 }
861                         }
862
863                         if (this is CheckedListBox)
864                                 rect.Width += 15;
865                                 
866                         return rect;
867                 }
868
869                 [EditorBrowsable (EditorBrowsableState.Advanced)]
870                 protected override Rectangle GetScaledBounds (Rectangle bounds, SizeF factor, BoundsSpecified specified)
871                 {
872                         bounds.Height = requested_height;
873
874                         return base.GetScaledBounds (bounds, factor, specified);
875                 }
876
877                 public bool GetSelected (int index)
878                 {
879                         if (index < 0 || index >= Items.Count)
880                                 throw new ArgumentOutOfRangeException ("Index of out range");
881
882                         return SelectedIndices.Contains (index);
883                 }
884
885                 public int IndexFromPoint (Point p)
886                 {
887                         return IndexFromPoint (p.X, p.Y);
888                 }
889
890                 // Only returns visible points
891                 public int IndexFromPoint (int x, int y)
892                 {
893
894                         if (Items.Count == 0) {
895                                 return -1;
896                         }
897
898                         for (int i = top_index; i <= last_visible_index; i++) {
899                                 if (GetItemRectangle (i).Contains (x,y) == true)
900                                         return i;
901                         }
902
903                         return -1;
904                 }
905
906                 protected override void OnChangeUICues (UICuesEventArgs e)
907                 {
908                         base.OnChangeUICues (e);
909                 }
910
911                 protected override void OnDataSourceChanged (EventArgs e)
912                 {
913                         base.OnDataSourceChanged (e);
914                         BindDataItems ();
915                         
916                         if (DataSource == null || DataManager == null) {
917                                 SelectedIndex = -1;
918                         } else {
919                                 SelectedIndex = DataManager.Position;
920                         }
921                 }
922
923                 protected override void OnDisplayMemberChanged (EventArgs e)
924                 {
925                         base.OnDisplayMemberChanged (e);
926
927                         if (DataManager == null || !IsHandleCreated)
928                                 return;
929
930                         BindDataItems ();
931                         base.Refresh ();
932                 }
933
934                 protected virtual void OnDrawItem (DrawItemEventArgs e)
935                 {                       
936                         switch (DrawMode) {
937                         case DrawMode.OwnerDrawFixed:
938                         case DrawMode.OwnerDrawVariable:
939                                 DrawItemEventHandler eh = (DrawItemEventHandler)(Events [DrawItemEvent]);
940                                 if (eh != null)
941                                         eh (this, e);
942
943                                 break;
944
945                         default:
946                                 ThemeEngine.Current.DrawListBoxItem (this, e);
947                                 break;
948                         }
949                 }
950
951                 protected override void OnFontChanged (EventArgs e)
952                 {
953                         base.OnFontChanged (e);
954
955                         if (use_tabstops)
956                                 StringFormat.SetTabStops (0, new float [] {(float)(Font.Height * 3.7)});
957
958                         if (explicit_item_height) {
959                                 base.Refresh ();
960                         } else {
961                                 SizeF sz = TextRenderer.MeasureString ("The quick brown Fox", Font);
962                                 item_height = (int) sz.Height;
963                                 if (IntegralHeight)
964                                         UpdateListBoxBounds ();
965                                 LayoutListBox ();
966                         }
967                 }
968
969                 protected override void OnHandleCreated (EventArgs e)
970                 {
971                         base.OnHandleCreated (e);
972
973                         if (IntegralHeight)
974                                 UpdateListBoxBounds ();
975
976                         LayoutListBox ();
977                         EnsureVisible (focused_item);
978                 }
979
980                 protected override void OnHandleDestroyed (EventArgs e)
981                 {
982                         base.OnHandleDestroyed (e);
983                 }
984
985                 protected virtual void OnMeasureItem (MeasureItemEventArgs e)
986                 {
987                         if (draw_mode != DrawMode.OwnerDrawVariable)
988                                 return;
989
990                         MeasureItemEventHandler eh = (MeasureItemEventHandler)(Events [MeasureItemEvent]);
991                         if (eh != null)
992                                 eh (this, e);
993                 }
994
995                 protected override void OnParentChanged (EventArgs e)
996                 {
997                         base.OnParentChanged (e);
998                 }
999
1000                 protected override void OnResize (EventArgs e)
1001                 {
1002                         base.OnResize (e);
1003                         if (canvas_size.IsEmpty || MultiColumn)
1004                                 LayoutListBox ();
1005                                 
1006                         Invalidate ();
1007                 }
1008
1009                 protected override void OnSelectedIndexChanged (EventArgs e)
1010                 {
1011                         base.OnSelectedIndexChanged (e);
1012
1013                         EventHandler eh = (EventHandler)(Events [SelectedIndexChangedEvent]);
1014                         if (eh != null)
1015                                 eh (this, e);
1016                 }
1017
1018                 protected override void OnSelectedValueChanged (EventArgs e)
1019                 {
1020                         base.OnSelectedValueChanged (e);
1021                 }
1022
1023                 public override void Refresh ()
1024                 {
1025                         if (draw_mode == DrawMode.OwnerDrawVariable)
1026                                 item_heights.Clear ();
1027                         
1028                         base.Refresh ();
1029                 }
1030
1031                 protected override void RefreshItem (int index)
1032                 {
1033                         if (index < 0 || index >= Items.Count)
1034                                 throw new ArgumentOutOfRangeException ("Index of out range");
1035                                 
1036                         if (draw_mode == DrawMode.OwnerDrawVariable)
1037                                 item_heights.Remove (Items [index]);
1038                 }
1039
1040                 protected override void RefreshItems ()
1041                 {
1042                         for (int i = 0; i < Items.Count; i++) {
1043                                 RefreshItem (i);
1044                         }
1045
1046                         LayoutListBox ();
1047                         Refresh ();
1048                 }
1049
1050                 public override void ResetBackColor ()
1051                 {
1052                         base.ResetBackColor ();
1053                 }
1054
1055                 public override void ResetForeColor ()
1056                 {
1057                         base.ResetForeColor ();
1058                 }
1059
1060                 protected override void ScaleControl (SizeF factor, BoundsSpecified specified)
1061                 {
1062                         base.ScaleControl (factor, specified);
1063                 }
1064
1065                 private int SnapHeightToIntegral (int height)
1066                 {
1067                         int border;
1068
1069                         switch (border_style) {
1070                         case BorderStyle.Fixed3D:
1071                                 border = ThemeEngine.Current.Border3DSize.Height;
1072                                 break;
1073                         case BorderStyle.FixedSingle:
1074                                 border = ThemeEngine.Current.BorderSize.Height;
1075                                 break;
1076                         case BorderStyle.None:
1077                         default:
1078                                 border = 0;
1079                                 break;
1080                         }
1081
1082                         height -= (2 * border);
1083                         height -= height % ItemHeight;
1084                         height += (2 * border);
1085
1086                         return height;
1087                 }
1088                 
1089                 protected override void SetBoundsCore (int x,  int y, int width, int height, BoundsSpecified specified)
1090                 {
1091                         if ((specified & BoundsSpecified.Height) == BoundsSpecified.Height)
1092                                 requested_height = height;
1093
1094                         if (IntegralHeight && IsHandleCreated)
1095                                 height = SnapHeightToIntegral (height);
1096
1097                         base.SetBoundsCore (x, y, width, height, specified);
1098                         UpdateScrollBars ();
1099                         last_visible_index = LastVisibleItem ();
1100                 }
1101
1102                 protected override void SetItemCore (int index,  object value)
1103                 {
1104                         if (index < 0 || index >= Items.Count)
1105                                 return;
1106
1107                         Items[index] = value;
1108                 }
1109
1110                 protected override void SetItemsCore (IList value)
1111                 {
1112                         BeginUpdate ();
1113                         try {
1114                                 Items.Clear ();
1115                                 Items.AddItems (value);
1116                         } finally {
1117                                 EndUpdate ();
1118                         }
1119                 }
1120
1121                 public void SetSelected (int index, bool value)
1122                 {
1123                         if (index < 0 || index >= Items.Count)
1124                                 throw new ArgumentOutOfRangeException ("Index of out range");
1125
1126                         if (SelectionMode == SelectionMode.None)
1127                                 throw new InvalidOperationException ();
1128
1129                         if (value)
1130                                 SelectedIndices.Add (index);
1131                         else
1132                                 SelectedIndices.Remove (index);
1133                 }
1134
1135                 protected virtual void Sort ()
1136                 {
1137                         Sort (true);
1138                 }
1139
1140                 //
1141                 // Sometimes we could need to Sort, and request a Refresh
1142                 // in a different place, to not have the painting done twice
1143                 //
1144                 void Sort (bool paint)
1145                 {
1146                         if (Items.Count == 0)
1147                                 return;
1148
1149                         Items.Sort ();
1150
1151                         if (paint)
1152                                 base.Refresh ();
1153                 }
1154
1155                 public override string ToString ()
1156                 {
1157                         return base.ToString ();
1158                 }
1159
1160                 protected virtual void WmReflectCommand (ref Message m)
1161                 {
1162                 }
1163
1164                 protected override void WndProc (ref Message m)
1165                 {
1166                         if ((Msg)m.Msg == Msg.WM_KEYDOWN) {
1167                                 if (ProcessKeyMessage (ref m))
1168                                         m.Result = IntPtr.Zero;
1169                                 else {
1170                                         HandleKeyDown ((Keys)m.WParam.ToInt32 ());
1171                                         DefWndProc (ref m);
1172                                 }
1173
1174                                 return;
1175                         }
1176
1177                         base.WndProc (ref m);
1178                 }
1179
1180                 #endregion Public Methods
1181
1182                 #region Private Methods
1183
1184                 private void CalculateTabStops ()
1185                 {
1186                         if (use_tabstops) {
1187                                 if (use_custom_tab_offsets) {
1188                                         float[] f = new float[custom_tab_offsets.Count];
1189                                         custom_tab_offsets.CopyTo (f, 0);
1190                                         StringFormat.SetTabStops (0, f);
1191                                 }
1192                                 else
1193                                         StringFormat.SetTabStops (0, new float[] { (float)(Font.Height * 3.7) });
1194                         } else
1195                                 StringFormat.SetTabStops (0, new float[0]);
1196
1197                         this.Invalidate ();
1198                 }
1199
1200                 private Size canvas_size;
1201
1202                 private void LayoutListBox ()
1203                 {
1204                         if (!IsHandleCreated || suspend_layout)
1205                                 return;
1206
1207                         if (MultiColumn)
1208                                 LayoutMultiColumn ();
1209                         else
1210                                 LayoutSingleColumn ();
1211
1212                         last_visible_index = LastVisibleItem ();
1213                         UpdateScrollBars ();
1214                 }
1215
1216                 private void LayoutSingleColumn ()
1217                 {
1218                         int height, width;
1219
1220                         switch (DrawMode) {
1221                         case DrawMode.OwnerDrawVariable:
1222                                 height = 0;
1223                                 width = HorizontalExtent;
1224                                 for (int i = 0; i < Items.Count; i++) {
1225                                         height += GetItemHeight (i);
1226                                 }
1227                                 break;
1228
1229                         case DrawMode.OwnerDrawFixed:
1230                                 height = Items.Count * ItemHeight;
1231                                 width = HorizontalExtent;
1232                                 break;
1233
1234                         case DrawMode.Normal:
1235                         default:
1236                                 height = Items.Count * ItemHeight;
1237                                 width = 0;
1238                                 for (int i = 0; i < Items.Count; i++) {
1239                                         SizeF sz = TextRenderer.MeasureString (GetItemText (Items[i]), Font);
1240                                         int t = (int)sz.Width;
1241                                         
1242                                         if (this is CheckedListBox)
1243                                                 t += 15;
1244                                                 
1245                                         if (t > width)
1246                                                 width = t;
1247                                 }
1248                                 break;
1249                         }
1250
1251                         canvas_size = new Size (width, height);
1252                 }
1253
1254                 private void LayoutMultiColumn ()
1255                 {
1256                         int usable_height = ClientRectangle.Height - (ScrollAlwaysVisible ? hscrollbar.Height : 0);
1257                         row_count = Math.Max (1, usable_height / ItemHeight);
1258
1259                         int cols = (int) Math.Ceiling ((float)Items.Count / (float) row_count);
1260                         Size sz = new Size (cols * ColumnWidthInternal, row_count * ItemHeight);
1261                         if (!ScrollAlwaysVisible && sz.Width > ClientRectangle.Width && row_count > 1) {
1262                                 usable_height = ClientRectangle.Height - hscrollbar.Height;
1263                                 row_count = Math.Max (1, usable_height / ItemHeight);
1264                                 cols = (int) Math.Ceiling ((float)Items.Count / (float) row_count);
1265                                 sz = new Size (cols * ColumnWidthInternal, row_count * ItemHeight);
1266                         }
1267                         canvas_size = sz;
1268                 }
1269
1270                 internal void Draw (Rectangle clip, Graphics dc)
1271                 {
1272                         Theme theme = ThemeEngine.Current;
1273
1274                         if (hscrollbar.Visible && vscrollbar.Visible) {
1275                                 // Paint the dead space in the bottom right corner
1276                                 Rectangle rect = new Rectangle (hscrollbar.Right, vscrollbar.Bottom, vscrollbar.Width, hscrollbar.Height);
1277                                 if (rect.IntersectsWith (clip))
1278                                         dc.FillRectangle (theme.ResPool.GetSolidBrush (theme.ColorControl), rect);
1279                         }
1280
1281                         dc.FillRectangle (theme.ResPool.GetSolidBrush (BackColor), items_area);
1282
1283                         if (Items.Count == 0)
1284                                 return;
1285
1286                         for (int i = top_index; i <= last_visible_index; i++) {
1287                                 Rectangle rect = GetItemDisplayRectangle (i, top_index);
1288
1289                                 if (!clip.IntersectsWith (rect))
1290                                         continue;
1291
1292                                 DrawItemState state = DrawItemState.None;
1293
1294                                 if (SelectedIndices.Contains (i))
1295                                         state |= DrawItemState.Selected;
1296                                         
1297                                 if (has_focus && FocusedItem == i)
1298                                         state |= DrawItemState.Focus;
1299                                         
1300                                 if (MultiColumn == false && hscrollbar != null && hscrollbar.Visible) {
1301                                         rect.X -= hscrollbar.Value;
1302                                         rect.Width += hscrollbar.Value;
1303                                 }
1304
1305                                 Color fore_color = (state & DrawItemState.Selected) != 0 ? ThemeEngine.Current.ColorHighlightText : ForeColor;
1306                                 OnDrawItem (new DrawItemEventArgs (dc, Font, rect, i, state, fore_color, BackColor));
1307                         }
1308                 }
1309
1310                 // Converts a GetItemRectangle to a one that we can display
1311                 internal Rectangle GetItemDisplayRectangle (int index, int first_displayble)
1312                 {
1313                         Rectangle item_rect;
1314                         Rectangle first_item_rect = GetItemRectangle (first_displayble);
1315                         item_rect = GetItemRectangle (index);
1316                         item_rect.X -= first_item_rect.X;
1317                         item_rect.Y -= first_item_rect.Y;
1318                         
1319                         // Subtract the checkboxes from the width
1320                         if (this is CheckedListBox)
1321                                 item_rect.Width -= 14;
1322
1323                         return item_rect;
1324                 }
1325
1326                 // Value Changed
1327                 private void HorizontalScrollEvent (object sender, EventArgs e)
1328                 {
1329                         if (multicolumn) {
1330                                 int top_item = top_index;
1331                                 int last_item = last_visible_index;
1332
1333                                 top_index = RowCount * hscrollbar.Value;
1334                                 last_visible_index = LastVisibleItem ();
1335
1336                                 if (top_item != top_index || last_item != last_visible_index)
1337                                         Invalidate (items_area);
1338                         }
1339                         else {
1340                                 int old_offset = hbar_offset;
1341                                 hbar_offset = hscrollbar.Value;
1342
1343                                 if (hbar_offset < 0)
1344                                         hbar_offset = 0;
1345
1346                                 if (IsHandleCreated) {
1347                                         XplatUI.ScrollWindow (Handle, items_area, old_offset - hbar_offset, 0, false);
1348
1349                                         // Invalidate the previous selection border, to keep it properly updated.
1350                                         Rectangle selection_border_area = new Rectangle (items_area.Width - (hbar_offset - old_offset) - 3, 0, 
1351                                                         3, items_area.Height);
1352                                         Invalidate (selection_border_area);
1353                                 }
1354                         }
1355                 }
1356
1357                 // Only returns visible points. The diference of with IndexFromPoint is that the rectangle
1358                 // has screen coordinates
1359                 private int IndexAtClientPoint (int x, int y)
1360                 {       
1361                         if (Items.Count == 0)
1362                                 return -1;
1363                         
1364                         if (x < 0)
1365                                 x = 0;
1366                         else if (x > ClientRectangle.Right)
1367                                 x = ClientRectangle.Right;
1368
1369                         if (y < 0)
1370                                 y = 0;
1371                         else if (y > ClientRectangle.Bottom)
1372                                 y = ClientRectangle.Bottom;
1373
1374                         for (int i = top_index; i <= last_visible_index; i++)
1375                                 if (GetItemDisplayRectangle (i, top_index).Contains (x, y))
1376                                         return i;
1377
1378                         return -1;
1379                 }
1380
1381                 internal override bool IsInputCharInternal (char charCode)
1382                 {
1383                         return true;
1384                 }
1385
1386                 private int LastVisibleItem ()
1387                 {
1388                         Rectangle item_rect;
1389                         int top_y = items_area.Y + items_area.Height;
1390                         int i = 0;
1391
1392                         if (top_index >= Items.Count)
1393                                 return top_index;
1394
1395                         for (i = top_index; i < Items.Count; i++) {
1396                                 item_rect = GetItemDisplayRectangle (i, top_index);
1397                                 if (MultiColumn) {
1398                                         if (item_rect.X > items_area.Width)
1399                                                 return i - 1;
1400                                 } else {
1401                                         if (item_rect.Y + item_rect.Height > top_y)
1402                                                 return i;
1403                                 }
1404                         }
1405                         return i - 1;
1406                 }
1407
1408                 private void UpdateTopItem ()
1409                 {
1410                         if (MultiColumn) {
1411                                 int col = top_index / RowCount;
1412                                 
1413                                 if (col > hscrollbar.Maximum)
1414                                         hscrollbar.Value = hscrollbar.Maximum;
1415                                 else
1416                                         hscrollbar.Value = col;
1417                         } else {
1418                                 if (top_index > vscrollbar.Maximum)
1419                                         vscrollbar.Value = vscrollbar.Maximum;
1420                                 else
1421                                         vscrollbar.Value = top_index;
1422                                 Scroll (vscrollbar, vscrollbar.Value - top_index);
1423                         }
1424                 }
1425                 
1426                 // Navigates to the indicated item and returns the new item
1427                 private int NavigateItemVisually (ItemNavigation navigation)
1428                 {                       
1429                         int page_size, columns, selected_index = -1;
1430
1431                         if (multicolumn) {
1432                                 columns = items_area.Width / ColumnWidthInternal; 
1433                                 page_size = columns * RowCount;
1434                                 if (page_size == 0) {
1435                                         page_size = RowCount;
1436                                 }
1437                         } else {
1438                                 page_size = items_area.Height / ItemHeight;     
1439                         }
1440
1441                         switch (navigation) {
1442
1443                         case ItemNavigation.PreviousColumn: {
1444                                 if (SelectedIndex - RowCount < 0) {
1445                                         return -1;
1446                                 }
1447
1448                                 if (SelectedIndex - RowCount < top_index) {
1449                                         top_index = SelectedIndex - RowCount;
1450                                         UpdateTopItem ();
1451                                 }
1452                                         
1453                                 selected_index = SelectedIndex - RowCount;
1454                                 break;
1455                         }
1456                         
1457                         case ItemNavigation.NextColumn: {
1458                                 if (SelectedIndex + RowCount >= Items.Count) {
1459                                         break;
1460                                 }
1461
1462                                 if (SelectedIndex + RowCount > last_visible_index) {
1463                                         top_index = SelectedIndex;
1464                                         UpdateTopItem ();
1465                                 }
1466                                         
1467                                 selected_index = SelectedIndex + RowCount;
1468                                 break;
1469                         }
1470
1471                         case ItemNavigation.First: {
1472                                 top_index = 0;
1473                                 selected_index  = 0;
1474                                 UpdateTopItem ();
1475                                 break;
1476                         }
1477
1478                         case ItemNavigation.Last: {
1479
1480                                 int rows = items_area.Height / ItemHeight;
1481                                 
1482                                 if (multicolumn) {
1483                                         selected_index = Items.Count - 1;
1484                                         break;
1485                                 }
1486                                 if (Items.Count < rows) {
1487                                         top_index = 0;
1488                                         selected_index  = Items.Count - 1;
1489                                         UpdateTopItem ();
1490                                 } else {
1491                                         top_index = Items.Count - rows;
1492                                         selected_index  = Items.Count - 1;
1493                                         UpdateTopItem ();
1494                                 }
1495                                 break;
1496                         }
1497
1498                         case ItemNavigation.Next: {
1499                                 if (FocusedItem == Items.Count - 1)
1500                                         return -1;
1501
1502                                 if (multicolumn) {
1503                                         selected_index = FocusedItem + 1;
1504                                         break;
1505                                 }
1506                                 
1507                                 int bottom = 0;
1508                                 ArrayList heights = new ArrayList ();
1509                                 if (draw_mode == DrawMode.OwnerDrawVariable) {
1510                                         for (int i = top_index; i <= FocusedItem + 1; i++) {
1511                                                 int h = GetItemHeight (i);
1512                                                 bottom += h;
1513                                                 heights.Add (h);
1514                                         }
1515                                 } else {
1516                                         bottom = ((FocusedItem + 1) - top_index + 1) * ItemHeight;
1517                                 }
1518
1519                                 if (bottom >= items_area.Height) {
1520                                         int overhang = bottom - items_area.Height;
1521
1522                                         int offset = 0;
1523                                         if (draw_mode == DrawMode.OwnerDrawVariable)
1524                                                 while (overhang > 0)
1525                                                         overhang -= (int) heights [offset];
1526                                         else
1527                                                 offset = (int) Math.Ceiling ((float)overhang / (float) ItemHeight);
1528                                         top_index += offset;
1529                                         UpdateTopItem ();
1530                                 }
1531                                 selected_index = FocusedItem + 1;
1532                                 break;
1533                         }
1534
1535                         case ItemNavigation.Previous: {
1536                                 if (FocusedItem > 0) {
1537                                         if (FocusedItem - 1 < top_index) {
1538                                                 top_index--;
1539                                                 UpdateTopItem ();
1540                                         }
1541                                         selected_index = FocusedItem - 1;
1542                                 }
1543                                 break;
1544                         }
1545
1546                         case ItemNavigation.NextPage: {
1547                                 if (Items.Count < page_size) {
1548                                         NavigateItemVisually (ItemNavigation.Last);
1549                                         break;
1550                                 }
1551
1552                                 if (FocusedItem + page_size - 1 >= Items.Count) {
1553                                         top_index = Items.Count - page_size;
1554                                         UpdateTopItem ();
1555                                         selected_index = Items.Count - 1;
1556                                 }
1557                                 else {
1558                                         if (FocusedItem + page_size - 1  > last_visible_index) {
1559                                                 top_index = FocusedItem;
1560                                                 UpdateTopItem ();
1561                                         }
1562                                         
1563                                         selected_index = FocusedItem + page_size - 1;
1564                                 }
1565                                         
1566                                 break;
1567                         }                       
1568
1569                         case ItemNavigation.PreviousPage: {
1570                                         
1571                                 int rows = items_area.Height / ItemHeight;
1572                                 if (FocusedItem - (rows - 1) <= 0) {
1573                                         top_index = 0;
1574                                         UpdateTopItem ();
1575                                         selected_index = 0;
1576                                 }
1577                                 else { 
1578                                         if (SelectedIndex - (rows - 1)  < top_index) {
1579                                                 top_index = FocusedItem - (rows - 1);
1580                                                 UpdateTopItem ();
1581                                         }
1582                                         
1583                                         selected_index = FocusedItem - (rows - 1);
1584                                 }
1585                                         
1586                                 break;
1587                         }               
1588                         default:
1589                                 break;
1590                         }
1591                         
1592                         return selected_index;
1593                 }
1594                 
1595                 
1596                 private void OnGotFocus (object sender, EventArgs e)
1597                 {
1598                         if (Items.Count == 0)
1599                                 return;
1600
1601                         if (FocusedItem == -1)
1602                                 FocusedItem = 0;
1603
1604                         InvalidateItem (FocusedItem);
1605                 }
1606                 
1607                 private void OnLostFocus (object sender, EventArgs e)
1608                 {
1609                         if (FocusedItem != -1)
1610                                 InvalidateItem (FocusedItem);
1611                 }
1612
1613                 private bool KeySearch (Keys key)
1614                 {
1615                         char c = (char) key;
1616                         if (!Char.IsLetterOrDigit (c))
1617                                 return false;
1618
1619                         int idx = FindString (c.ToString (), SelectedIndex);
1620                         if (idx != ListBox.NoMatches)
1621                                 SelectedIndex = idx;
1622
1623                         return true;
1624                 }
1625
1626                 internal void HandleKeyDown (Keys key)
1627                 {
1628                         int new_item = -1;
1629                         
1630                         if (Items.Count == 0)
1631                                 return;
1632
1633                         if (KeySearch (key))
1634                                 return;
1635
1636                         switch (key) {
1637                                 
1638                                 case Keys.ControlKey:
1639                                         ctrl_pressed = true;
1640                                         break;
1641                                         
1642                                 case Keys.ShiftKey:
1643                                         shift_pressed = true;
1644                                         break;
1645                                         
1646                                 case Keys.Home:
1647                                         new_item = NavigateItemVisually (ItemNavigation.First);
1648                                         break;
1649
1650                                 case Keys.End:
1651                                         new_item = NavigateItemVisually (ItemNavigation.Last);
1652                                         break;
1653
1654                                 case Keys.Up:
1655                                         new_item = NavigateItemVisually (ItemNavigation.Previous);
1656                                         break;
1657         
1658                                 case Keys.Down:
1659                                         new_item = NavigateItemVisually (ItemNavigation.Next);
1660                                         break;
1661                                 
1662                                 case Keys.PageUp:
1663                                         new_item = NavigateItemVisually (ItemNavigation.PreviousPage);
1664                                         break;
1665         
1666                                 case Keys.PageDown:
1667                                         new_item = NavigateItemVisually (ItemNavigation.NextPage);
1668                                         break;
1669
1670                                 case Keys.Right:
1671                                         if (multicolumn == true) {
1672                                                 new_item = NavigateItemVisually (ItemNavigation.NextColumn);
1673                                         }
1674                                         break;
1675         
1676                                 case Keys.Left:
1677                                         if (multicolumn == true) {
1678                                                 new_item = NavigateItemVisually (ItemNavigation.PreviousColumn);
1679                                         }
1680                                         break;
1681                                         
1682                                 case Keys.Space:
1683                                         if (selection_mode == SelectionMode.MultiSimple) {
1684                                                 SelectedItemFromNavigation (FocusedItem);
1685                                         }
1686                                         break;
1687                                 
1688
1689                                 default:
1690                                         break;
1691                                 }
1692                                 
1693                                 if (new_item != -1) {
1694                                         FocusedItem = new_item;
1695
1696                                         if (selection_mode != SelectionMode.MultiSimple)
1697                                                 SelectedItemFromNavigation (new_item);
1698                                 }
1699                 }
1700                 
1701                 private void OnKeyUpLB (object sender, KeyEventArgs e)
1702                 {
1703                         switch (e.KeyCode) {
1704                                 case Keys.ControlKey:
1705                                         ctrl_pressed = false;
1706                                         break;
1707                                 case Keys.ShiftKey:
1708                                         shift_pressed = false;
1709                                         break;
1710                                 default: 
1711                                         break;
1712                         }
1713                 }
1714
1715                 internal void InvalidateItem (int index)
1716                 {
1717                         if (!IsHandleCreated)
1718                                 return;
1719                         Rectangle bounds = GetItemDisplayRectangle (index, top_index);
1720                         if (ClientRectangle.IntersectsWith (bounds))
1721                                 Invalidate (bounds);
1722                 }
1723
1724                 internal virtual void OnItemClick (int index)
1725                 {
1726                         OnSelectedIndexChanged  (EventArgs.Empty);
1727                         OnSelectedValueChanged (EventArgs.Empty);
1728                 }
1729
1730                 int anchor = -1;
1731                 int[] prev_selection;
1732                 bool button_pressed = false;
1733                 Point button_pressed_loc = new Point (-1, -1);
1734
1735                 private void SelectExtended (int index)
1736                 {
1737                         SuspendLayout ();
1738
1739                         ArrayList new_selection = new ArrayList ();
1740                         int start = anchor < index ? anchor : index;
1741                         int end = anchor > index ? anchor : index;
1742                         for (int i = start; i <= end; i++)
1743                                 new_selection.Add (i);
1744
1745                         if (ctrl_pressed)
1746                                 foreach (int i in prev_selection)
1747                                         if (!new_selection.Contains (i))
1748                                                 new_selection.Add (i);
1749
1750                         // Need to make a copy since we can't enumerate and modify the collection
1751                         // at the same time
1752                         ArrayList sel_indices = (ArrayList) selected_indices.List.Clone ();
1753                         foreach (int i in sel_indices)
1754                                 if (!new_selection.Contains (i))
1755                                         selected_indices.Remove (i);
1756
1757                         foreach (int i in new_selection)
1758                                 if (!sel_indices.Contains (i))
1759                                         selected_indices.AddCore (i);
1760                         ResumeLayout ();
1761                 }
1762
1763                 private void OnMouseDownLB (object sender, MouseEventArgs e)
1764                 {
1765                         // Only do stuff with the left mouse button
1766                         if ((e.Button & MouseButtons.Left) == 0)
1767                                 return;
1768                         
1769                         int index = IndexAtClientPoint (e.X, e.Y);
1770                         if (index == -1)
1771                                 return;
1772
1773                         switch (SelectionMode) {
1774                         case SelectionMode.One:
1775                                 SelectedIndices.AddCore (index); // Unselects previous one
1776                                 break;
1777
1778                         case SelectionMode.MultiSimple:
1779                                 if (SelectedIndices.Contains (index))
1780                                         SelectedIndices.RemoveCore (index);
1781                                 else
1782                                         SelectedIndices.AddCore (index);
1783                                 break;
1784
1785                         case SelectionMode.MultiExtended:
1786                                 shift_pressed = (XplatUI.State.ModifierKeys & Keys.Shift) != 0;
1787                                 ctrl_pressed = (XplatUI.State.ModifierKeys & Keys.Control) != 0;
1788
1789                                 if (shift_pressed) {
1790                                         SelectedIndices.ClearCore ();
1791                                         SelectExtended (index);
1792                                         break;
1793                                 }
1794
1795                                 anchor = index;
1796
1797                                 if (ctrl_pressed) {
1798                                         prev_selection = new int [SelectedIndices.Count];
1799                                         SelectedIndices.CopyTo (prev_selection, 0);
1800
1801                                         if (SelectedIndices.Contains (index))
1802                                                 SelectedIndices.RemoveCore (index);
1803                                         else
1804                                                 SelectedIndices.AddCore (index);
1805
1806                                         break;
1807                                 }
1808
1809                                 SelectedIndices.ClearCore ();
1810                                 SelectedIndices.AddCore (index);
1811                                 break;
1812
1813                         case SelectionMode.None:
1814                                 break;
1815                         default:
1816                                 return;
1817                         }
1818
1819                         button_pressed = true;
1820                         button_pressed_loc = new Point (e.X, e.Y);
1821                         FocusedItem = index;
1822                 }
1823
1824                 private void OnMouseMoveLB (object sender, MouseEventArgs e)
1825                 {
1826                         // Don't take into account MouseMove events generated with MouseDown
1827                         if (!button_pressed || button_pressed_loc == new Point (e.X, e.Y))
1828                                 return;
1829
1830                         int index = IndexAtClientPoint (e.X, e.Y);
1831                         if (index == -1)
1832                                 return;
1833
1834                         switch (SelectionMode) {
1835                         case SelectionMode.One:
1836                                 SelectedIndices.AddCore (index); // Unselects previous one
1837                                 break;
1838
1839                         case SelectionMode.MultiSimple:
1840                                 break;
1841
1842                         case SelectionMode.MultiExtended:
1843                                 SelectExtended (index);
1844                                 break;
1845
1846                         case SelectionMode.None:
1847                                 break;
1848                         default:
1849                                 return;
1850                         }
1851
1852                         FocusedItem = index;
1853                 }
1854
1855                 internal override void OnDragDropEnd (DragDropEffects effects)
1856                 {
1857                         // In the case of a DnD operation (started on MouseDown)
1858                         // there will be no MouseUp event, so we need to reset 
1859                         // the state here
1860                         button_pressed = false;
1861                 }
1862
1863                 private void OnMouseUpLB (object sender, MouseEventArgs e)
1864                 {
1865                         // Only do stuff with the left mouse button
1866                         if ((e.Button & MouseButtons.Left) == 0)
1867                                 return;
1868
1869                         if (e.Clicks > 1) {
1870                                 OnDoubleClick (EventArgs.Empty);
1871                                 OnMouseDoubleClick (e);
1872                         }
1873                         else if (e.Clicks == 1) {
1874                                 OnClick (EventArgs.Empty);
1875                                 OnMouseClick (e);
1876                         }
1877                         
1878                         if (!button_pressed)
1879                                 return;
1880
1881                         int index = IndexAtClientPoint (e.X, e.Y);
1882                         OnItemClick (index);
1883                         button_pressed = ctrl_pressed = shift_pressed = false;
1884                 }
1885
1886                 private void Scroll (ScrollBar scrollbar, int delta)
1887                 {
1888                         if (delta == 0 || !scrollbar.Visible || !scrollbar.Enabled)
1889                                 return;
1890
1891                         int max;
1892                         if (scrollbar == hscrollbar)
1893                                 max = hscrollbar.Maximum - (items_area.Width / ColumnWidthInternal) + 1;
1894                         else
1895                                 max = vscrollbar.Maximum - (items_area.Height / ItemHeight) + 1;
1896
1897                         int val = scrollbar.Value + delta;
1898                         if (val > max)
1899                                 val = max;
1900                         else if (val < scrollbar.Minimum)
1901                                 val = scrollbar.Minimum;
1902                         scrollbar.Value = val;
1903                 }
1904
1905                 private void OnMouseWheelLB (object sender, MouseEventArgs me)
1906                 {
1907                         if (Items.Count == 0)
1908                                 return;
1909
1910                         int lines = me.Delta / 120;
1911
1912                         if (MultiColumn)
1913                                 Scroll (hscrollbar, -SystemInformation.MouseWheelScrollLines * lines);
1914                         else
1915                                 Scroll (vscrollbar, -lines);
1916                 }
1917
1918                 internal override void OnPaintInternal (PaintEventArgs pevent)
1919                 {
1920                         if (suspend_layout)
1921                                 return;
1922
1923                         Draw (pevent.ClipRectangle, pevent.Graphics);
1924                 }
1925
1926                 internal void RepositionScrollBars ()
1927                 {
1928                         if (vscrollbar.is_visible) {
1929                                 vscrollbar.Size = new Size (vscrollbar.Width, items_area.Height);
1930                                 vscrollbar.Location = new Point (items_area.Width, 0);
1931                         }
1932
1933                         if (hscrollbar.is_visible) {
1934                                 hscrollbar.Size = new Size (items_area.Width, hscrollbar.Height);
1935                                 hscrollbar.Location = new Point (0, items_area.Height);
1936                         }
1937                 }
1938
1939                 // An item navigation operation (mouse or keyboard) has caused to select a new item
1940                 internal void SelectedItemFromNavigation (int index)
1941                 {
1942                         switch (SelectionMode) {
1943                                 case SelectionMode.None:
1944                                         // .Net doesn't select the item, only ensures that it's visible
1945                                         // and fires the selection related events
1946                                         EnsureVisible (index);
1947                                         OnSelectedIndexChanged (EventArgs.Empty);
1948                                         OnSelectedValueChanged (EventArgs.Empty);
1949                                         break;
1950                                 case SelectionMode.One: {
1951                                         SelectedIndex = index;
1952                                         break;
1953                                 }
1954                                 case SelectionMode.MultiSimple: {
1955                                         if (SelectedIndex == -1) {
1956                                                 SelectedIndex = index;
1957                                         } else {
1958
1959                                                 if (SelectedIndices.Contains (index))
1960                                                         SelectedIndices.Remove (index);
1961                                                 else {
1962                                                         SelectedIndices.AddCore (index);
1963
1964                                                         OnSelectedIndexChanged  (EventArgs.Empty);
1965                                                         OnSelectedValueChanged (EventArgs.Empty);
1966                                                 }
1967                                         }
1968                                         break;
1969                                 }
1970                                 
1971                                 case SelectionMode.MultiExtended: {
1972                                         if (SelectedIndex == -1) {
1973                                                 SelectedIndex = index;
1974                                         } else {
1975
1976                                                 if (ctrl_pressed == false && shift_pressed == false) {
1977                                                         SelectedIndices.Clear ();
1978                                                 }
1979                                                 
1980                                                 if (shift_pressed == true) {
1981                                                         ShiftSelection (index);
1982                                                 } else { // ctrl_pressed or single item
1983                                                         SelectedIndices.AddCore (index);
1984
1985                                                 }
1986
1987                                                 OnSelectedIndexChanged  (EventArgs.Empty);
1988                                                 OnSelectedValueChanged (EventArgs.Empty);
1989                                         }
1990                                         break;
1991                                 }
1992                                 
1993                                 default:
1994                                         break;
1995                         }
1996                 }
1997                 
1998                 private void ShiftSelection (int index)
1999                 {
2000                         int shorter_item = -1, dist = Items.Count + 1, cur_dist;
2001                         
2002                         foreach (int idx in selected_indices) {
2003                                 if (idx > index) {
2004                                         cur_dist = idx - index;
2005                                 } else {
2006                                         cur_dist = index - idx;
2007                                 }
2008
2009                                 if (cur_dist < dist) {
2010                                         dist = cur_dist;
2011                                         shorter_item = idx;
2012                                 }
2013                         }
2014                         
2015                         if (shorter_item != -1) {
2016                                 int start, end;
2017                                 
2018                                 if (shorter_item > index) {
2019                                         start = index;
2020                                         end = shorter_item;
2021                                 } else {
2022                                         start = shorter_item;
2023                                         end = index;
2024                                 }
2025                                 
2026                                 selected_indices.Clear ();
2027                                 for (int idx = start; idx <= end; idx++) {
2028                                         selected_indices.AddCore (idx);
2029                                 }
2030                         }
2031                 }
2032                 
2033                 internal int FocusedItem {
2034                         get { return focused_item; }
2035                         set {
2036                                 if (focused_item == value)
2037                                         return;
2038
2039                                 int prev = focused_item;
2040                         
2041                                 focused_item = value;
2042                         
2043                                 if (has_focus == false)
2044                                         return;
2045
2046                                 if (prev != -1)
2047                                         InvalidateItem (prev);
2048                         
2049                                 if (value != -1)
2050                                         InvalidateItem (value);
2051
2052                                 // UIA Framework: Generates FocusedItemChanged event.
2053                                 OnUIAFocusedItemChangedEvent ();
2054                         }
2055                 }
2056
2057                 StringFormat string_format;
2058                 internal StringFormat StringFormat {
2059                         get {
2060                                 if (string_format == null) {
2061                                         string_format = new StringFormat ();
2062                                         string_format.FormatFlags = StringFormatFlags.NoWrap;
2063
2064                                         if (RightToLeft == RightToLeft.Yes)
2065                                                 string_format.Alignment = StringAlignment.Far;
2066                                         else
2067                                                 string_format.Alignment = StringAlignment.Near;
2068                                         CalculateTabStops ();
2069                                 }
2070                                 return string_format;
2071                         }
2072                 }
2073
2074                 internal virtual void CollectionChanged ()
2075                 {
2076                         if (sorted) 
2077                                 Sort (false);
2078
2079                         if (Items.Count == 0) {
2080                                 selected_indices.List.Clear ();
2081                                 focused_item = -1;
2082                                 top_index = 0;
2083                         }
2084                         if (Items.Count <= focused_item)
2085                                 focused_item = Items.Count - 1;
2086
2087                         if (!IsHandleCreated || suspend_layout)
2088                                 return;
2089
2090                         LayoutListBox ();
2091
2092                         base.Refresh ();
2093                 }
2094
2095                 void EnsureVisible (int index)
2096                 {
2097                         if (!IsHandleCreated || index == -1)
2098                                 return;
2099
2100                         if (index < top_index) {
2101                                 top_index = index;
2102                                 UpdateTopItem ();
2103                                 Invalidate ();
2104                         } else if (!multicolumn) {
2105                                 int rows = items_area.Height / ItemHeight;
2106                                 if (index >= (top_index + rows))
2107                                         top_index = index - rows + 1;
2108
2109                                 UpdateTopItem ();
2110                         } else {
2111                                 int rows = Math.Max (1, items_area.Height / ItemHeight);
2112                                 int cols = Math.Max (1, items_area.Width / ColumnWidthInternal);
2113                                 
2114                                 if (index >= (top_index + (rows * cols))) {
2115                                         int incolumn = index / rows;
2116                                         top_index = (incolumn - (cols - 1)) * rows;
2117
2118                                         UpdateTopItem ();
2119                                         Invalidate ();
2120                                 }
2121                         }
2122                 }
2123
2124                 private void UpdateListBoxBounds ()
2125                 {
2126                         if (IsHandleCreated)
2127                                 SetBoundsInternal (bounds.X, bounds.Y, bounds.Width, IntegralHeight ? SnapHeightToIntegral (requested_height) : requested_height, BoundsSpecified.None);
2128                 }
2129
2130                 private void UpdateScrollBars ()
2131                 {
2132                         items_area = ClientRectangle;
2133                         if (UpdateHorizontalScrollBar ()) {
2134                                 items_area.Height -= hscrollbar.Height;
2135                                 if (UpdateVerticalScrollBar ()) {
2136                                         items_area.Width -= vscrollbar.Width;
2137                                         UpdateHorizontalScrollBar ();
2138                                 }
2139                         } else if (UpdateVerticalScrollBar ()) {
2140                                 items_area.Width -= vscrollbar.Width;
2141                                 if (UpdateHorizontalScrollBar ()) {
2142                                         items_area.Height -= hscrollbar.Height;
2143                                         UpdateVerticalScrollBar ();
2144                                 }
2145                         }
2146
2147                         RepositionScrollBars ();
2148                 }
2149
2150                 /* Determines if the horizontal scrollbar has to be displyed */
2151                 private bool UpdateHorizontalScrollBar ()
2152                 {
2153                         bool show = false;
2154                         bool enabled = true;
2155
2156                         if (MultiColumn) {
2157                                 if (canvas_size.Width > items_area.Width) {
2158                                         show = true;
2159                                         hscrollbar.Maximum  = canvas_size.Width / ColumnWidthInternal - 1;
2160                                 } else if (ScrollAlwaysVisible == true) {
2161                                         enabled = false;
2162                                         show = true;
2163                                         hscrollbar.Maximum  = 0;
2164                                 }
2165                         } else if (canvas_size.Width > ClientRectangle.Width && HorizontalScrollbar) {
2166                                 show = true;
2167                                 hscrollbar.Maximum = canvas_size.Width;
2168                                 hscrollbar.LargeChange = Math.Max (0, items_area.Width);
2169                         } else if (scroll_always_visible && horizontal_scrollbar) {
2170                                 show = true;
2171                                 enabled = false;
2172                                 hscrollbar.Maximum = 0;
2173                         }
2174
2175                         hbar_offset = hscrollbar.Value;
2176                         hscrollbar.Enabled = enabled;
2177                         hscrollbar.Visible = show;
2178
2179                         return show;
2180                 }
2181
2182                 /* Determines if the vertical scrollbar has to be displyed */
2183                 private bool UpdateVerticalScrollBar ()
2184                 {
2185                         if (MultiColumn || (Items.Count == 0 && !scroll_always_visible)) {
2186                                 vscrollbar.Visible = false;
2187                                 return false;
2188                         } else if (Items.Count == 0) {
2189                                 vscrollbar.Visible = true;
2190                                 vscrollbar.Enabled = false;
2191                                 vscrollbar.Maximum = 0;
2192                                 return true;
2193                         }
2194
2195                         bool show = false;
2196                         bool enabled = true;
2197                         if (canvas_size.Height > items_area.Height) {
2198                                 show = true;
2199                                 vscrollbar.Maximum = Items.Count - 1;
2200                                 vscrollbar.LargeChange = Math.Max (items_area.Height / ItemHeight, 0);
2201                         } else if (ScrollAlwaysVisible) {
2202                                 show = true;
2203                                 enabled = false;
2204                                 vscrollbar.Maximum = 0;
2205                         }
2206
2207                         vscrollbar.Enabled = enabled;
2208                         vscrollbar.Visible = show;
2209
2210                         return show;
2211                 }
2212
2213                 // Value Changed
2214                 private void VerticalScrollEvent (object sender, EventArgs e)
2215                 {
2216                         int top_item = top_index;
2217
2218                         top_index = /*row_count + */ vscrollbar.Value;
2219                         last_visible_index = LastVisibleItem ();
2220
2221                         int delta = (top_item - top_index) * ItemHeight;
2222                         if (DrawMode == DrawMode.OwnerDrawVariable) {
2223                                 delta = 0;
2224
2225                                 if (top_index < top_item)
2226                                         for (int i = top_index; i < top_item; i++)
2227                                                 delta += GetItemHeight (i);
2228                                 else 
2229                                         for (int i = top_item; i < top_index; i++)
2230                                                 delta -= GetItemHeight (i);
2231                         }
2232
2233                         if (IsHandleCreated)
2234                                 XplatUI.ScrollWindow (Handle, items_area, 0, delta, false);
2235                 }
2236
2237                 #endregion Private Methods
2238
2239                 public class IntegerCollection : IList, ICollection, IEnumerable
2240                 {
2241                         private ListBox owner;
2242                         private List<int> list;
2243                         
2244                         #region Public Constructor
2245                         public IntegerCollection (ListBox owner)
2246                         {
2247                                 this.owner = owner;
2248                                 list = new List<int> ();
2249                         }
2250                         #endregion
2251
2252                         #region Public Properties
2253                         [Browsable (false)]
2254                         public int Count {
2255                                 get { return list.Count; }
2256                         }
2257                         
2258                         public int this [int index] {
2259                                 get { return list[index]; }
2260                                 set { list[index] = value; owner.CalculateTabStops (); }
2261                         }
2262                         #endregion
2263
2264                         #region Public Methods
2265                         public int Add (int item)
2266                         {
2267                                 // This collection does not allow duplicates
2268                                 if (!list.Contains (item)) {
2269                                         list.Add (item);
2270                                         list.Sort ();
2271                                         owner.CalculateTabStops ();
2272                                 }
2273                                 
2274                                 return list.IndexOf (item);
2275                         }
2276                         
2277                         public void AddRange (int[] items)
2278                         {
2279                                 AddItems (items);
2280                         }
2281                         
2282                         public void AddRange (IntegerCollection value)
2283                         {
2284                                 AddItems (value);
2285                         }
2286
2287                         void AddItems (IList items)
2288                         {
2289                                 if (items == null)
2290                                         throw new ArgumentNullException ("items");
2291
2292                                 foreach (int i in items)
2293                                         if (!list.Contains (i))
2294                                                 list.Add (i);
2295
2296                                 list.Sort ();
2297                         }
2298
2299                         public void Clear ()
2300                         {
2301                                 list.Clear ();
2302                                 owner.CalculateTabStops ();
2303                         }
2304                         
2305                         public bool Contains (int item)
2306                         {
2307                                 return list.Contains (item);
2308                         }
2309                         
2310                         public void CopyTo (Array destination, int index)
2311                         {
2312                                 for (int i = 0; i < list.Count; i++)
2313                                         destination.SetValue (list[i], index++);
2314                         }
2315                         
2316                         public int IndexOf (int item)
2317                         {
2318                                 return list.IndexOf (item);
2319                         }
2320                         
2321                         public void Remove (int item)
2322                         {
2323                                 list.Remove (item);
2324                                 list.Sort ();
2325                                 owner.CalculateTabStops ();
2326                         }
2327                         
2328                         public void RemoveAt (int index)
2329                         {
2330                                 if (index < 0)
2331                                         throw new IndexOutOfRangeException ();
2332
2333                                 list.RemoveAt (index);
2334                                 list.Sort ();
2335                                 owner.CalculateTabStops ();
2336                         }
2337                         #endregion
2338
2339                         #region IEnumerable Members
2340                         IEnumerator IEnumerable.GetEnumerator ()
2341                         {
2342                                 return list.GetEnumerator ();
2343                         }
2344                         #endregion
2345
2346                         #region IList Members
2347                         int IList.Add (object item)
2348                         {
2349                                 int? intValue = item as int?;
2350                                 if (!intValue.HasValue)
2351                                         throw new ArgumentException ("item");
2352                                 return Add (intValue.Value);
2353                         }
2354
2355                         void IList.Clear ()
2356                         {
2357                                 Clear ();
2358                         }
2359
2360                         bool IList.Contains (object item)
2361                         {
2362                                 int? intValue = item as int?;
2363                                 if (!intValue.HasValue)
2364                                         return false;
2365                                 return Contains (intValue.Value);
2366                         }
2367
2368                         int IList.IndexOf (object item)
2369                         {
2370                                 int? intValue = item as int?;
2371                                 if (!intValue.HasValue)
2372                                         return -1;
2373                                 return IndexOf (intValue.Value);
2374                         }
2375
2376                         void IList.Insert (int index, object value)
2377                         {
2378                                 throw new NotSupportedException (string.Format (
2379                                         CultureInfo.InvariantCulture, "No items "
2380                                         + "can be inserted into {0}, since it is"
2381                                         + " a sorted collection.", this.GetType ()));
2382                         }
2383
2384                         bool IList.IsFixedSize
2385                         {
2386                                 get { return false; }
2387                         }
2388
2389                         bool IList.IsReadOnly
2390                         {
2391                                 get { return false; }
2392                         }
2393
2394                         void IList.Remove (object value)
2395                         {
2396                                 int? intValue = value as int?;
2397                                 if (!intValue.HasValue)
2398                                         throw new ArgumentException ("value");
2399
2400                                 Remove (intValue.Value);
2401                         }
2402
2403                         void IList.RemoveAt (int index)
2404                         {
2405                                 RemoveAt (index);
2406                         }
2407
2408                         object IList.this[int index] {
2409                                 get { return this[index]; }
2410                                 set { this[index] = (int)value; }
2411                         }
2412                         #endregion
2413
2414                         #region ICollection Members
2415                         bool ICollection.IsSynchronized {
2416                                 get { return true; }
2417                         }
2418
2419                         object ICollection.SyncRoot {
2420                                 get { return this; }
2421                         }
2422                         #endregion
2423                 }
2424
2425                 [ListBindable (false)]
2426                 public class ObjectCollection : IList, ICollection, IEnumerable
2427                 {
2428                         internal class ListObjectComparer : IComparer
2429                         {
2430                                 public int Compare (object a, object b)
2431                                 {
2432                                         string str1 = a.ToString ();
2433                                         string str2 = b.ToString ();
2434                                         return str1.CompareTo (str2);
2435                                 }
2436                         }
2437
2438                         private ListBox owner;
2439                         internal ArrayList object_items = new ArrayList ();
2440                         
2441                         #region UIA Framework Events 
2442                         //NOTE:
2443                         //      We are using Reflection to add/remove internal events.
2444                         //      Class ListProvider uses the events.
2445                         //
2446                         //Event used to generate UIA StructureChangedEvent
2447                         static object UIACollectionChangedEvent = new object ();
2448
2449                         internal event CollectionChangeEventHandler UIACollectionChanged {
2450                                 add { owner.Events.AddHandler (UIACollectionChangedEvent, value); }
2451                                 remove { owner.Events.RemoveHandler (UIACollectionChangedEvent, value); }
2452                         }
2453
2454                         internal void OnUIACollectionChangedEvent (CollectionChangeEventArgs args)
2455                         {
2456                                 CollectionChangeEventHandler eh
2457                                         = (CollectionChangeEventHandler) owner.Events [UIACollectionChangedEvent];
2458                                 if (eh != null)
2459                                         eh (owner, args);
2460                         }
2461                         #endregion UIA Framework Events 
2462
2463                         public ObjectCollection (ListBox owner)
2464                         {
2465                                 this.owner = owner;
2466                         }
2467
2468                         public ObjectCollection (ListBox owner, object[] value)
2469                         {
2470                                 this.owner = owner;
2471                                 AddRange (value);
2472                         }
2473
2474                         public ObjectCollection (ListBox owner,  ObjectCollection value)
2475                         {
2476                                 this.owner = owner;
2477                                 AddRange (value);
2478                         }
2479
2480                         #region Public Properties
2481                         public int Count {
2482                                 get { return object_items.Count; }
2483                         }
2484
2485                         public bool IsReadOnly {
2486                                 get { return false; }
2487                         }
2488
2489                         [Browsable(false)]
2490                         [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2491                         public virtual object this [int index] {
2492                                 get {
2493                                         if (index < 0 || index >= Count)
2494                                                 throw new ArgumentOutOfRangeException ("Index of out range");
2495
2496                                         return object_items[index];
2497                                 }
2498                                 set {
2499                                         if (index < 0 || index >= Count)
2500                                                 throw new ArgumentOutOfRangeException ("Index of out range");
2501                                         if (value == null)
2502                                                 throw new ArgumentNullException ("value");
2503                                                 
2504                                         //UIA Framework event: Item Removed
2505                                         OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Remove, object_items [index]));
2506
2507                                         object_items[index] = value;
2508                                         
2509                                         //UIA Framework event: Item Added
2510                                         OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Add, value));
2511
2512                                         owner.CollectionChanged ();
2513                                 }
2514                         }
2515
2516                         bool ICollection.IsSynchronized {
2517                                 get { return false; }
2518                         }
2519
2520                         object ICollection.SyncRoot {
2521                                 get { return this; }
2522                         }
2523
2524                         bool IList.IsFixedSize {
2525                                 get { return false; }
2526                         }
2527
2528                         #endregion Public Properties
2529                         
2530                         #region Public Methods
2531                         public int Add (object item)
2532                         {
2533                                 int idx;
2534
2535                                 idx = AddItem (item);
2536                                 owner.CollectionChanged ();
2537                                 
2538                                 // If we are sorted, the item probably moved indexes, get the real one
2539                                 if (owner.sorted)
2540                                         return this.IndexOf (item);
2541                                         
2542                                 return idx;
2543                         }
2544
2545                         public void AddRange (object[] items)
2546                         {
2547                                 AddItems (items);
2548                         }
2549
2550                         public void AddRange (ObjectCollection value)
2551                         {
2552                                 AddItems (value);
2553                         }
2554
2555                         internal void AddItems (IList items)
2556                         {
2557                                 if (items == null)
2558                                         throw new ArgumentNullException ("items");
2559
2560                                 foreach (object mi in items)
2561                                         AddItem (mi);
2562
2563                                 owner.CollectionChanged ();
2564                         }
2565
2566                         public virtual void Clear ()
2567                         {
2568                                 owner.selected_indices.ClearCore ();
2569                                 object_items.Clear ();
2570                                 owner.CollectionChanged ();
2571
2572                                 //UIA Framework event: Items list cleared
2573                                 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Refresh, null));
2574                         }
2575
2576                         public bool Contains (object value)
2577                         {
2578                                 if (value == null)
2579                                         throw new ArgumentNullException ("value");
2580
2581                                 return object_items.Contains (value);
2582                         }
2583
2584                         public void CopyTo (object[] destination, int arrayIndex)
2585                         {
2586                                 object_items.CopyTo (destination, arrayIndex);
2587                         }
2588
2589                         void ICollection.CopyTo (Array destination, int index)
2590                         {
2591                                 object_items.CopyTo (destination, index);
2592                         }
2593
2594                         public IEnumerator GetEnumerator ()
2595                         {
2596                                 return object_items.GetEnumerator ();
2597                         }
2598
2599                         int IList.Add (object item)
2600                         {
2601                                 return Add (item);
2602                         }
2603
2604                         public int IndexOf (object value)
2605                         {
2606                                 if (value == null)
2607                                         throw new ArgumentNullException ("value");
2608
2609                                 return object_items.IndexOf (value);
2610                         }
2611
2612                         public void Insert (int index,  object item)
2613                         {
2614                                 if (index < 0 || index > Count)
2615                                         throw new ArgumentOutOfRangeException ("Index of out range");
2616                                 if (item == null)
2617                                         throw new ArgumentNullException ("item");
2618                                         
2619                                 owner.BeginUpdate ();
2620                                 object_items.Insert (index, item);
2621                                 owner.CollectionChanged ();
2622                                 owner.EndUpdate ();
2623                                 
2624                                 //UIA Framework event: Item Added
2625                                 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Add, item));
2626                         }
2627
2628                         public void Remove (object value)
2629                         {
2630                                 if (value == null)
2631                                         return;
2632
2633                                 int index = IndexOf (value);
2634                                 if (index != -1)
2635                                         RemoveAt (index);
2636                         }
2637
2638                         public void RemoveAt (int index)
2639                         {
2640                                 if (index < 0 || index >= Count)
2641                                         throw new ArgumentOutOfRangeException ("Index of out range");
2642
2643                                 //UIA Framework element removed
2644                                 object removed = object_items [index];
2645                                 UpdateSelection (index);
2646                                 object_items.RemoveAt (index);
2647                                 owner.CollectionChanged ();
2648
2649                                 //UIA Framework event: Item Removed
2650                                 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Remove, removed));
2651                         }
2652                         #endregion Public Methods
2653
2654                         #region Private Methods
2655                         internal int AddItem (object item)
2656                         {
2657                                 if (item == null)
2658                                         throw new ArgumentNullException ("item");
2659
2660                                 int cnt = object_items.Count;
2661                                 object_items.Add (item);
2662
2663                                 //UIA Framework event: Item Added
2664                                 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Add, item));
2665
2666                                 return cnt;
2667                         }
2668
2669                         // we receive the index to be removed
2670                         void UpdateSelection (int removed_index)
2671                         {
2672                                 owner.selected_indices.Remove (removed_index);
2673
2674                                 if (owner.selection_mode != SelectionMode.None) {
2675                                         int last_idx = object_items.Count - 1;
2676
2677                                         // if the last item was selected, remove it from selection,
2678                                         // since it will become invalid after the removal
2679                                         if (owner.selected_indices.Contains (last_idx)) {
2680                                                 owner.selected_indices.Remove (last_idx);
2681
2682                                                 // in SelectionMode.One try to put the selection on the new last item
2683                                                 int new_idx = last_idx - 1;
2684                                                 if (owner.selection_mode == SelectionMode.One && new_idx > -1)
2685                                                         owner.selected_indices.Add (new_idx);
2686                                         }
2687                                 }
2688
2689                         }
2690
2691                         internal void Sort ()
2692                         {
2693                                 object_items.Sort (new ListObjectComparer ());
2694                         }
2695
2696                         #endregion Private Methods
2697                 }
2698
2699                 public class SelectedIndexCollection : IList, ICollection, IEnumerable
2700                 {
2701                         private ListBox owner;
2702                         ArrayList selection;
2703                         bool sorting_needed; // Selection state retrieval is done sorted - we do it lazyly
2704
2705                         #region UIA Framework Events 
2706
2707                         //NOTE:
2708                         //      We are using Reflection to add/remove internal events.
2709                         //      Class ListProvider uses the events.
2710                         //
2711                         //Event used to generate UIA StructureChangedEvent
2712                         static object UIACollectionChangedEvent = new object ();
2713
2714                         internal event CollectionChangeEventHandler UIACollectionChanged {
2715                                 add { owner.Events.AddHandler (UIACollectionChangedEvent, value); }
2716                                 remove { owner.Events.RemoveHandler (UIACollectionChangedEvent, value); }
2717                         }
2718
2719                         internal void OnUIACollectionChangedEvent (CollectionChangeEventArgs args)
2720                         {
2721                                 CollectionChangeEventHandler eh
2722                                         = (CollectionChangeEventHandler) owner.Events [UIACollectionChangedEvent];
2723                                 if (eh != null)
2724                                         eh (owner, args);
2725                         }
2726
2727                         #endregion UIA Framework Events 
2728
2729
2730                         public SelectedIndexCollection (ListBox owner)
2731                         {
2732                                 this.owner = owner;
2733                                 selection = new ArrayList ();
2734                         }
2735
2736                         #region Public Properties
2737                         [Browsable (false)]
2738                         public int Count {
2739                                 get { return selection.Count; }
2740                         }
2741
2742                         public bool IsReadOnly {
2743                                 get { return true; }
2744                         }
2745
2746                         public int this [int index] {
2747                                 get {
2748                                         if (index < 0 || index >= Count)
2749                                                 throw new ArgumentOutOfRangeException ("Index of out range");
2750
2751                                         CheckSorted ();
2752                                         return (int)selection [index];
2753                                 }
2754                         }
2755
2756                         bool ICollection.IsSynchronized {
2757                                 get { return true; }
2758                         }
2759
2760                         bool IList.IsFixedSize{
2761                                 get { return true; }
2762                         }
2763
2764                         object ICollection.SyncRoot {
2765                                 get { return selection; }
2766                         }
2767
2768                         #endregion Public Properties
2769
2770                         #region Public Methods
2771                         public void Add (int index)
2772                         {
2773                                 if (AddCore (index)) {
2774                                         owner.OnSelectedIndexChanged (EventArgs.Empty);
2775                                         owner.OnSelectedValueChanged (EventArgs.Empty);
2776                                 }
2777                         }
2778
2779                         // Need to separate selection logic from events,
2780                         // since selection changes using keys/mouse handle them their own way
2781                         internal bool AddCore (int index)
2782                         {
2783                                 if (selection.Contains (index))
2784                                         return false;
2785
2786                                 if (index == -1) // Weird MS behaviour
2787                                         return false;
2788                                 if (index < -1 || index >= owner.Items.Count)
2789                                         throw new ArgumentOutOfRangeException ("index");
2790                                 if (owner.selection_mode == SelectionMode.None)
2791                                         throw new InvalidOperationException ("Cannot call this method when selection mode is SelectionMode.None");
2792
2793                                 if (owner.selection_mode == SelectionMode.One && Count > 0) // Unselect previously selected item
2794                                         RemoveCore ((int)selection [0]);
2795
2796                                 selection.Add (index);
2797                                 sorting_needed = true;
2798                                 owner.EnsureVisible (index);
2799                                 owner.FocusedItem = index;
2800                                 owner.InvalidateItem (index);
2801
2802                                 // UIA Framework event: Selected item added
2803                                 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Add, index));
2804
2805                                 return true;
2806                         }
2807
2808                         public void Clear ()
2809                         {
2810                                 if (ClearCore ()) {
2811                                         owner.OnSelectedIndexChanged (EventArgs.Empty);
2812                                         owner.OnSelectedValueChanged (EventArgs.Empty);
2813                                 }
2814                         }
2815
2816                         internal bool ClearCore ()
2817                         {
2818                                 if (selection.Count == 0)
2819                                         return false;
2820
2821                                 foreach (int index in selection)
2822                                         owner.InvalidateItem (index);
2823
2824                                 selection.Clear ();
2825
2826                                 // UIA Framework event: Selected items list updated
2827                                 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Refresh, -1));
2828
2829                                 return true;
2830                         }
2831
2832                         public bool Contains (int selectedIndex)
2833                         {
2834                                 foreach (int index in selection)
2835                                         if (index == selectedIndex)
2836                                                 return true;
2837                                 return false;
2838                         }
2839
2840                         public void CopyTo (Array destination, int index)
2841                         {
2842                                 CheckSorted ();
2843                                 selection.CopyTo (destination, index);
2844                         }
2845
2846                         public IEnumerator GetEnumerator ()
2847                         {
2848                                 CheckSorted ();
2849                                 return selection.GetEnumerator ();
2850                         }
2851
2852                         // FIXME: Probably we can avoid sorting when calling
2853                         // IndexOf (imagine a scenario where multiple removal of items
2854                         // happens)
2855                         public void Remove (int index)
2856                         {
2857                                 // Separate logic from events here too
2858                                 if (RemoveCore (index)) {
2859                                         owner.OnSelectedIndexChanged (EventArgs.Empty);
2860                                         owner.OnSelectedValueChanged (EventArgs.Empty);
2861                                 }
2862                         }
2863
2864                         internal bool RemoveCore (int index)
2865                         {
2866                                 int idx = IndexOf (index);
2867                                 if (idx == -1)
2868                                         return false;
2869
2870                                 selection.RemoveAt (idx);
2871                                 owner.InvalidateItem (index);
2872
2873                                 // UIA Framework event: Selected item removed from selection
2874                                 OnUIACollectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Remove, index));
2875
2876                                 return true;
2877                         }
2878
2879                         int IList.Add (object value)
2880                         {
2881                                 throw new NotSupportedException ();
2882                         }
2883
2884                         void IList.Clear ()
2885                         {
2886                                 throw new NotSupportedException ();
2887                         }
2888
2889                         bool IList.Contains (object selectedIndex)
2890                         {
2891                                 return Contains ((int)selectedIndex);
2892                         }
2893
2894                         int IList.IndexOf (object selectedIndex)
2895                         {
2896                                 return IndexOf ((int) selectedIndex);
2897                         }
2898
2899                         void IList.Insert (int index, object value)
2900                         {
2901                                 throw new NotSupportedException ();
2902                         }
2903
2904                         void IList.Remove (object value)
2905                         {
2906                                 throw new NotSupportedException ();
2907                         }
2908
2909                         void IList.RemoveAt (int index)
2910                         {
2911                                 throw new NotSupportedException ();
2912                         }
2913
2914                         object IList.this[int index]{
2915                                 get { return this [index]; }
2916                                 set {throw new NotImplementedException (); }
2917                         }
2918
2919                         public int IndexOf (int selectedIndex)
2920                         {
2921                                 CheckSorted ();
2922
2923                                 for (int i = 0; i < selection.Count; i++)
2924                                         if ((int)selection [i] == selectedIndex)
2925                                                 return i;
2926
2927                                 return -1;
2928                         }
2929                         #endregion Public Methods
2930                         internal ArrayList List {
2931                                 get {
2932                                         CheckSorted ();
2933                                         return selection;
2934                                 }
2935                         }
2936
2937                         void CheckSorted ()
2938                         {
2939                                 if (sorting_needed) {
2940                                         sorting_needed = false;
2941                                         selection.Sort ();
2942                                 }
2943                         }
2944                 }
2945
2946                 public class SelectedObjectCollection : IList, ICollection, IEnumerable
2947                 {
2948                         private ListBox owner;
2949
2950                         public SelectedObjectCollection (ListBox owner)
2951                         {
2952                                 this.owner = owner;
2953                         }
2954
2955                         #region Public Properties
2956                         public int Count {
2957                                 get { return owner.selected_indices.Count; }
2958                         }
2959
2960                         public bool IsReadOnly {
2961                                 get { return true; }
2962                         }
2963
2964                         [Browsable(false)]
2965                         [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2966                         public object this [int index] {
2967                                 get {
2968                                         if (index < 0 || index >= Count)
2969                                                 throw new ArgumentOutOfRangeException ("Index of out range");
2970
2971                                         return owner.items [owner.selected_indices [index]];
2972                                 }
2973                                 set {throw new NotSupportedException ();}
2974                         }
2975
2976                         bool ICollection.IsSynchronized {
2977                                 get { return true; }
2978                         }
2979
2980                         object ICollection.SyncRoot {
2981                                 get { return this; }
2982                         }
2983
2984                         bool IList.IsFixedSize {
2985                                 get { return true; }
2986                         }
2987
2988                         #endregion Public Properties
2989
2990                         #region Public Methods
2991                         public void Add (object value)
2992                         {
2993                                 if (owner.selection_mode == SelectionMode.None)
2994                                         throw new ArgumentException ("Cannot call this method if SelectionMode is SelectionMode.None");
2995
2996                                 int idx = owner.items.IndexOf (value);
2997                                 if (idx == -1)
2998                                         return;
2999
3000                                 owner.selected_indices.Add (idx);
3001                         }
3002
3003                         public void Clear ()
3004                         {
3005                                 owner.selected_indices.Clear ();
3006                         }
3007
3008                         public bool Contains (object selectedObject)
3009                         {
3010                                 int idx = owner.items.IndexOf (selectedObject);
3011                                 return idx == -1 ? false : owner.selected_indices.Contains (idx);
3012                         }
3013
3014                         public void CopyTo (Array destination, int index)
3015                         {
3016                                 for (int i = 0; i < Count; i++)
3017                                         destination.SetValue (this [i], index++);
3018                         }
3019
3020                         public void Remove (object value)
3021                         {
3022                                 if (value == null)
3023                                         return;
3024
3025                                 int idx = owner.items.IndexOf (value);
3026                                 if (idx == -1)
3027                                         return;
3028
3029                                 owner.selected_indices.Remove (idx);
3030                         }
3031
3032                         int IList.Add (object value)
3033                         {
3034                                 throw new NotSupportedException ();
3035                         }
3036
3037                         void IList.Clear ()
3038                         {
3039                                 throw new NotSupportedException ();
3040                         }
3041
3042                         void IList.Insert (int index, object value)
3043                         {
3044                                 throw new NotSupportedException ();
3045                         }
3046
3047                         void IList.Remove (object value)
3048                         {
3049                                 throw new NotSupportedException ();
3050                         }
3051
3052                         void IList.RemoveAt (int index)
3053                         {
3054                                 throw new NotSupportedException ();
3055                         }
3056         
3057                         public int IndexOf (object selectedObject)
3058                         {
3059                                 int idx = owner.items.IndexOf (selectedObject);
3060                                 return idx == -1 ? -1 : owner.selected_indices.IndexOf (idx);
3061                         }
3062
3063                         public IEnumerator GetEnumerator ()
3064                         {
3065                                 //FIXME: write an enumerator that uses selection.GetEnumerator
3066                                 //  so that invalidation is write on selection changes
3067                                 object [] items = new object [Count];
3068                                 for (int i = 0; i < Count; i++) {
3069                                         items [i] = owner.items [owner.selected_indices [i]];
3070                                 }
3071
3072                                 return items.GetEnumerator ();
3073                         }
3074
3075                         #endregion Public Methods
3076                 }
3077         }
3078 }