[C#][Control]指撥開關控制項的概念與簡易實作
private SwitchState _state;
public SwitchState State
{
get
{
return _state;
}
set
{
if (_state == value)
return;
_state = value;
AdjustOnOffButton();
}
}
private void AdjustOnOffButton()
{
switch (State)
{
case SwitchState.On:
OnOffButton.Dock = DockStyle.Top;
break;
case SwitchState.Off:
OnOffButton.Dock = DockStyle.Bottom;
break;
default:
break;
}
}</pre>
private void OnOffButton_Click(object sender, EventArgs e)
{
Toggle();
}</pre>
namespace WindowsFormsApplication3 { public partial class SwitchButton : UserControl {
public enum SwitchState
{
On,
Off
}
private SwitchState _state;
public SwitchState State
{
get
{
return _state;
}
set
{
if (_state == value)
return;
_state = value;
AdjustOnOffButton();
}
}
public SwitchButton()
{
InitializeComponent();
State = SwitchState.Off;
}
private void AdjustOnOffButton()
{
switch (State)
{
case SwitchState.On:
OnOffButton.Dock = DockStyle.Top;
break;
case SwitchState.Off:
OnOffButton.Dock = DockStyle.Bottom;
break;
default:
break;
}
}
public void Toggle()
{
State = State == SwitchState.On? SwitchState.Off: SwitchState.On;
}
private void SwitchButton_SizeChanged(object sender, EventArgs e)
{
OnOffButton.Height = this.Height / 2;
}
private void OnOffButton_Click(object sender, EventArgs e)
{
Toggle();
}
}
}