原文:http://www.dotblogs.com.tw/yc421206/archive/2012/03/29/71131.aspx
我有SwitchFlag類別
public class SwitchFlag
{
private bool _Enable = false;
public bool Enable
{
get { return _Enable; }
set { _Enable = value; }
}
private bool _IsTabStop=true;
public bool IsTabStop
{
get { return _IsTabStop; }
set { _IsTabStop = value; }
}
}
Dictionary 集合這樣定義
private Dictionary<Control, SwitchFlag> _SwitchFlags = new Dictionary<Control, SwitchFlag>();
public Dictionary<Control, SwitchFlag> SwitchFlags
{
get { return _SwitchFlags; }
set { _SwitchFlags = value; }
}
查詢Dictionary 集合的索引,這樣寫
int findControlIndex(Control ctrl)
{
int position = SwitchFlags
.Select((item, index) => new { Ctrl = item.Key, Index = index })
.Where(i => i.Ctrl.Name == ctrl.Name).First().Index
;
return position;
}
依索引條件找出集合物件
Control moveControl(int position)
{
var move = SwitchFlags
.Select((item, index) => new { Ctrl = item.Key, Index = index })
.Where(o => o.Index == (position)).First().Ctrl
;
return move;
}
呼叫上述兩個方法
void Ctrl_KeyDown(object sender, KeyEventArgs e)
{
Control current = (Control)sender;
if (!this.SwitchFlags.ContainsKey(current))
{
return;
}
int index = findControlIndex(current);//找出集合索引
int count = this.SwitchFlags.Count;
Control move = null;
if (this.NextKeys.Contains(e.KeyCode))
{
if (index == count - 1)
{
move = moveControl(0);
}
else
{
move = moveControl(index + 1);//找出下一個物件
}
}
else if (this.PreviousKeys.Contains(e.KeyCode))
{
if (index == 0)
{
move = moveControl(count - 1);
}
else
{
move = moveControl(index - 1);//找出上一個物件
}
}
move.Focus();
}
實作結果
若有謬誤,煩請告知,新手發帖請多包涵