强制转换文本框KeyEventArgs



我正试图在运行时为textBox控件获取KeyUp事件,但我很难正确转换。下面的代码编译后,当我添加监视/检查rtbPrivateNote_KeyUp时,我可以看到事件信息->EventArgs e:

public class Form1
{
private System.Windows.Controls.TextBox rtbPrivateNote = null;

public InitFormControls()
{
LoadSpellChecker(ref pnlPrivateNotes, ref rtbPrivateNote, "txtPrivateNotePanel");
rtbPrivateNote.TextChanged += new System.Windows.Controls.TextChangedEventHandler(rtbPrivateNote_TextChanged);
rtbPrivateNote.KeyUp += new System.Windows.Input.KeyEventHandler(rtbPrivateNote_KeyUp);
}

private void LoadSpellChecker(ref Panel panelRichText, ref System.Windows.Controls.TextBox txtWithSpell, string ControlName)
{
txtWithSpell = new System.Windows.Controls.TextBox
{
Name = ControlName
};
txtWithSpell.SpellCheck.IsEnabled = true;
txtWithSpell.Width = panelRichText.Width;
txtWithSpell.Height = panelRichText.Height;
txtWithSpell.AcceptsReturn = true;
txtWithSpell.AcceptsTab = true;
txtWithSpell.AllowDrop = true;
txtWithSpell.IsReadOnly = false;
txtWithSpell.TextWrapping = System.Windows.TextWrapping.Wrap;

ElementHost elementHost = new ElementHost
{
Dock = DockStyle.Fill,
Child = txtWithSpell
};

panelRichText.Controls.Add(elementHost);
}

// private void rtbPrivateNote_KeyUp(object sender, KeyEventArgs e)  // WONT COMPILE
private void rtbPrivateNote_KeyUp(object sender, EventArgs e)
{
//if (e.Key == Key.Enter  
//    || e.Key == Key.Return)
//{
//    Do Something here
//}
}
}

您不能这样强制转换它,因为KeyEventArgs派生自EventArgs,并且由于e不是KeyEventArg,它说它不能强制转换。

如果e的类型是KeyEventArgs,那么您可以将其强制转换为EventArgs。

private void rtbPrivateNote_KeyUp(object sender, EventArgs e)
{
KeyEventArgs ke = e as KeyEventArgs;
if (ke != null)
{
if (ke.Key == Key.Enter  || ke.Key == Key.Return)
{
//Do Something here
}
}
}

最新更新