Thursday, October 25. 2007CardLayout Implementation for CSharpThis article provides a simple Card Layout implementation for C# Windows Forms. CardPanel, our CardLayout implementation, keeps other Controls as Cards, and allows you to switch between them by only showing a single one at any given time. CardLayout is very popular in Java AWT based GUI programming. However, C# Windows Forms, does not provide a replacement like System.Windows.Forms.CardLayout. CardPanel is a simple CardLayout implementation for C#. You can also use the CardPanel in VisualStudio Design Mode. Simply add your other controls into the CardPanel, then change the Current property using the Property Editor, to the Name of the control that you would like to show. Here is a quick example: // Fill the area with CardPanel CardPanel cardPanel = new CardPanel(); cardPanel.Dock = DockStyle.Fill; Controls.Add(cardPanel); // Create our controls Button button1 = new Button(); button1.Text = "button1"; Button button2 = new Button(); button2.Text = "button2"; // We need to name our control in order to be able to // use them with our CardPanel button1.Name = "button1"; button2.Name = "button2"; // Add them to our CardPanel cardPanel.Controls.Add(button1); cardPanel.Controls.Add(button2); // Now switch to button2 cardPanel.Current = "button2"; // Now switch to button1 cardPanel.Current = "button1"; Here is our CardPanel.cs code:
//
// Copyright (c) 2007 by A. Onur Cinar
// Provided under LGPL license.
// http://www.zdo.com
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
namespace Zdo.UI
{
class CardPanel : Panel
{
#region Fields
string current;
#endregion
#region Properties
public string Current
{
get { return current; }
set
{
if (current.Equals(value))
return;
if (!Controls.ContainsKey(value))
return;
if (!current.Equals(String.Empty))
Controls[current].Visible = false;
Controls[value].Visible = true;
current = value;
}
}
#endregion
#region Constructor
public CardPanel ()
{
current = String.Empty;
}
#endregion
#region Handlers
protected override void OnControlAdded (ControlEventArgs e)
{
e.Control.Dock = DockStyle.Fill;
Current = e.Control.Name;
base.OnControlAdded(e);
}
protected override void OnControlRemoved (ControlEventArgs e)
{
if (current.Equals(e.Control.Name))
current = String.Empty;
base.OnControlRemoved(e);
}
#endregion
}
}
If you found this post helpful, please "Kick" it so others can find it too: Trackbacks
Trackback specific URI for this entry
No Trackbacks
|