在Smartphone2003中,如果界面中有ListView控件,则无法与其它控件切换了。如下图:

Smartphone2003中实现焦点在ListView控件与其它控件中切换

在上图中,如果焦点切换到了ListView中后,就无法切换回TextBox等控件上了,非常不方便操作。

因此在这里,我扩展了ListView控件,参考代码如下:

public class ListViewEx : ListView
    {
        public ListViewEx()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }

        /// <summary>
        /// 处理上下控件的焦点切换
        /// </summary>
        /// <param name="e"></param>
        protected override void OnKeyDown(KeyEventArgs e)
        {
            int index = -1;
            bool up = false;
            bool next = false;

            if (this.Items.Count == 0)
            {
                up = true;
            }
            if (this.SelectedIndices.Count > 0 && this.SelectedIndices[0] == 0)
            {
                up = true;
            }
            if (this.SelectedIndices.Count > 0 && this.SelectedIndices[0] == this.Items.Count - 1)
            {
                next = true;
            }

            switch (e.KeyCode)
            {
                case Keys.Down:
                    if (next)
                    {
                        index = this.Parent.Controls.GetChildIndex(this);
                        do
                        {
                            if ((index + 1) == this.Parent.Controls.Count)
                                index = -1; //roll over
                            index++;
                        } while (!IsFocusable(this.Parent.Controls[index]));
                    }
                    break;

                case Keys.Up:
                    if (up)
                    {
                        index = this.Parent.Controls.GetChildIndex(this);
                        do
                        {
                            if (index == 0)
                                index = this.Parent.Controls.Count; //roll over
                            index--;
                        } while (!IsFocusable(this.Parent.Controls[index]));
                    }
                    break;
            }
            if (index > -1 && index < this.Parent.Controls.Count)
            {
                this.Parent.Controls[index].Focus();
                return;
            }
            base.OnKeyDown(e);
        }

        private bool IsFocusable(Control control)
        {
            if (control is Label)
                return false;
            else
                return true;
        }
    }

相关文章: