【问题标题】:Casting Textbox KeyEventArgs投射文本框 KeyEventArgs
【发布时间】:2020-12-07 22:21:36
【问题描述】:

我正在尝试在运行时获取 textBox 控件的 KeyUp 事件,但我正在努力正确转换。下面的代码编译,当我添加 Watch/Inspect 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
        //}
    }
}

【问题讨论】:

  • 您正在混合 WinForms 和 WPF 控件/代码。您订阅的事件有 WPF KeyEventArgs 而不是 WinForms 的默认值 KeyEventArgs
  • 你为什么要通过ref传递panelRichText
  • @flydog 我正在使用面板在运行时保持文本控件。
  • @IvanStoev 没有使用 WPF 控件 - 我想你看到了我从以前使用的一些代码中复制的控件名称“WPFControlName” - 我现在重命名了它,但它只是分配的控件名称
  • 我看到您在函数中使用了panelRichText 控件,但您没有更改参数的值。你不需要通过 ref 传递它。

标签: c# winforms events casting keyevent


【解决方案1】:

你不能那样转换它,因为 KeyEventArgs 派生自 EventArgs 并且由于 e 不是 KeyEventArgs,它说它不能转换它。

如果 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
       }
    }
}

【讨论】:

  • 您可以通过说 if (e is KeyEventArgs ke) 并去掉前一行(进行演员表)来简化这一点
  • 这毫无意义。再次阅读我在问题下的评论。您正在尝试转换为错误的类型。确保如果private void rtbPrivateNote_KeyUp(object sender, KeyEventArgs e) 不会编译,那么上面的if 将永远不会被输入。您只需在事件处理程序签名中使用正确的 KeyEventArgs 类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-23
  • 1970-01-01
  • 2018-02-10
  • 2016-08-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多