【问题标题】:Trying to implement "Enter" event handler to textbook尝试将“Enter”事件处理程序实现到教科书
【发布时间】:2015-07-23 18:05:01
【问题描述】:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Text.RegularExpressions;
using Microsoft.VisualBasic;



namespace HelloWorld
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        string filePathTEST = "";



        public MainWindow()
        {
            InitializeComponent();
            // Clearing text event handlers
            textBox1.GotFocus += textBox1_GotFocus;


            // Enter event handlers for textboxes
            textBox1.KeyDown += new System.Windows.Input.KeyEventHandler(textBox1_KeyDown);



        }

 static void textBox1_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                //enter key is down
            }
        }

我在尝试运行上述代码时遇到的错误如下:

不能隐式转换类型 'System.Windows.Forms.KeyEventHandler' 到 'System.Windows.Input.KeyEventHandler'

然后我尝试将代码更改为 System.Windows.Input,然后我得到以下信息:

错误 1 ​​'System.Windows.Input.KeyEventArgs' 不包含 'KeyCode' 的定义并且没有扩展方法 'KeyCode' 接受 'System.Windows.Input.KeyEventArgs' 类型的第一个参数可以是 找到(您是否缺少 using 指令或程序集引用?)

我这样做的全部意义在于,当我在文本框中按 Enter 键时,我想获取该文本框中的文本并用它填充某个文本文件,但我不知道该怎么做。

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    由于您添加的命名空间:System.Windows.Forms,编译器认为您的意思是使用“System.Windows.Forms.KeyEventHandler”。

    删除此行,您的代码应该可以工作:

    using System.Windows.Forms;
    

    其次,您应该使用 Key 而不是 KeyCode,因为那是 WPF 变体:

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Return)
        {
             //
        }
    }
    

    【讨论】:

    • 问题是如果我使用 System.Windows.Forms; 删除,那么我不能使用 OpenFileDialog() 方法
    【解决方案2】:

    您正在与 Windows 客户端开发相当混乱的状态发生冲突。 System.Windows.Forms 是 WinForms 库的一部分,WinForms 库是 .NET 1.0 附带的原始 UI 框架。您正在使用的项目是用 WPF(Windows 演示框架)编写的,这是在 .NET 3 中开始发布的新库。有很多重叠,但两个库是不同的。

    您想要的类是 System.Windows.Input.KeyEventArgs。如果您在 MSDN 上获取此类的文档,您会发现它实际上没有 KeyCode 属性。但是,它确实有一个 Key 属性,可以满足您的需求。

    我将把查找和阅读 MSDN 文档作为练习留给读者。 :-)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-15
      • 1970-01-01
      • 1970-01-01
      • 2015-01-12
      • 2020-02-07
      相关资源
      最近更新 更多