该需求来自一位群友公司的客户,耗资了两杯高端奶茶钱咨询我,在这里分享给大家。
具体需求是这样的,XtraTabControl界面,一个Page有GridControl,另外一个Page是其他编辑控件,当GridView选中了内容后,切换Page,点其他的控件,这个时候GridControl就会失去焦点,之前的选中的文本也会消失,所以再次切换到GridControl所在的Page的时候就会看不到之前选择的内容,总所周知,客户都是挑剔的魔鬼,他们就想切换回来的时候,界面还是之前的样子,当做什么事都没发生过(渣男无疑),既然他们有这种扭曲心理,我们就满足他们吧,免得他们嗷嗷叫。
实现逻辑是这样的
1、在GridControl失去焦点之前记录选中的文本的起始点和长度(即选中的范围)
2、当XtraTabControl切换回GridControl所在的page的时候,就让GridControl主动获取焦点,并且让GridView处于编辑状态,然后再去根据之前记录的范围去设置选中的范围
了解大致逻辑就直接上代码了,其中GridView注册LostFocus事件,XtraTabControl注册SelectedPageChanged事件
int selectionStart = -1;
int selectionLength = -1;
private void gridView1_LostFocus(object sender, EventArgs e)
{
var edit = gridView1.ActiveEditor as TextEdit;//处于编辑状态的控件
if (edit != null)
{
//记录此时选中的起点和长度
selectionStart = edit.SelectionStart;
selectionLength = edit.SelectionLength;
}
}
private void xtraTabControl1_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
{
//tabpage再次获得焦点的时候,让gridcontrol获得焦点,并且让gridView开启编辑状态,再设置之前记录选中文本的起点和长度
if (e.Page == xtraTabPage1 && selectionLength >= 0 && selectionStart >= 0)
{
gridControl1.Focus();
gridView1.ShowEditor();//开启编辑状态
var edit = gridView1.ActiveEditor as TextEdit;
if (edit != null)
{
//设置选中内容
edit.SelectionStart = selectionStart;
edit.SelectionLength = selectionLength;
//恢复初始值
selectionStart = -1;
selectionLength = -1;
}
}
}
效果图:
觉得有用的,记得打赏哦