Visual Studio 2010,C#
我有一个ComboBox
,DropDown
,AutoComplete
设置为SuggestAppend
,AutoCompleteSource
来自ListItems
。用户将数据键入其中,直到具有正确的条目。如果数据与其中一个列表项匹配,则组合框旁边的按钮将被禁用。
如果用户点击Tab键,则自动完成功能会接受当前建议。它还会移动到启用的选项卡序列中的下一个控件。当然,因为我希望它转到disbabled按钮,我需要在验证条目后立即启用它。
问题在于,我尝试过的所有事件,PreviewKeyDown
,LostFocus
,SelectedIndexChanged
都不允许我及时启用该按钮以便进行处理并获得焦点。它始终以Tab键顺序进入下一个按钮,该按钮始终处于启用状态。
我准备好让按钮保持启用状态,如果太快按下它就会出错,但我不想这样做。我也不想进入特殊模式标志来跟踪这些控件何时获得焦点。验证似乎是正常的事情,但我被困住了。
如果SelectedIndexChanged
在用户匹配时起作用,这将很容易。当盒子清除时或者找不到类型匹配时它不会触发。
答案 0 :(得分:1)
您可以创建自己的ComboBox类来封装此行为。像这样:
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.myComboBox1.TheButton = this.button1;
this.myComboBox1.Items.AddRange( new string[] {
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
} );
button1.Enabled = false;
}
}
public class MyComboBox : ComboBox
{
public Control TheButton { get; set; }
public MyComboBox()
{
}
bool IsValidItemSelected
{
get { return null != this.SelectedItem; }
}
protected override void OnValidated( EventArgs e )
{
if ( null != TheButton )
{
TheButton.Enabled = this.IsValidItemSelected;
TheButton.Focus();
}
base.OnValidated( e );
}
protected override void OnTextChanged( EventArgs e )
{
if ( null != TheButton )
{
TheButton.Enabled = this.IsValidItemSelected;
}
base.OnTextChanged( e );
}
}
}
答案 1 :(得分:0)
try this :
key_press事件:
if (e.KeyData == Keys.Enter)
{
button2.Enabled = true;
button2.Focus();
}
答案 2 :(得分:0)
而不是你提到的事件hanlders,(LostFocus,SelectedIndexChanged和PreviewKeyDown)使用组合框的“Validated”事件来设置按钮的启用状态。
您可能还需要手动对焦按钮以强制焦点移动到它。
e.g。
private void comboBox1_Validated(object sender, EventArgs e)
{
button1.Enabled = true;
button1.Focus();
}
答案 3 :(得分:0)
考虑到其他答案,我想出了一个不使用 AutoComplete 的部分Senario。副作用是第二次调用PreviewKeyDown事件,因此调用两次验证。我想知道为什么......也许我应该问另一个问题。
private void comboBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) {
if (e.KeyData == Keys.Tab) {
if (ValidationRoutine()) {
e.IsInputKey = true; //If Validated, signals KeyDown to examine this key
} //Side effect - This event is called twice when IsInputKey is set to true
}
}
private void comboBox1_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyData == Keys.Tab) {
e.SuppressKeyPress = true; //Stops further processing of the TAB key
btnEdit.Enabled = true;
btnEdit.Focus();
}
}
使用除AutoCompleteMode
以外的任何设置启用None
后,KeyDown
事件不会再触发Tab
该密钥被静默吃掉。