wpf 在事件 Keydown 中获取发件人文本框名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16128244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:38:32  来源:igfitidea点击:

Get Sender TextBox Name in Event Keydown

wpfc#-4.0textboxonkeydown

提问by Samarth Agarwal

I am working on an application using WPF and C#. On a window I have number of textBoxes arranged in a grid of 5 columns and rows as many as user needs. It works like this: Initially the 1st row of 5 textBoxes is visible, the user enters appropriate values and as soon as he hits ENTERin the 5th textBox of the row, a new similar row of textBoxes is generated for newer entries. This keep on happening. Each textBox has a unique name using RegisterNamemethod and loop.

我正在使用 WPF 和 C# 开发一个应用程序。在一个窗口上,我根据用户需要将多个文本框排列在 5 列和行的网格中。它是这样工作的:最初ENTER5 个文本框的第一行是可见的,用户输入适当的值,一旦他点击该行的第 5 个文本框,就会为较新的条目生成一个新的类似文本框行。这种情况一直在发生。每个文本框都有一个唯一的使用RegisterName方法和循环的名称。

Now my problem is that suppose I have already created 5 rows with around 25 textBoxes on window. I focus on one of the textBoxes of the 3rd row and type something that fires it appropriate KeyDown Event. In this keydown event, I need the Nameof all the textBox that caused this event. How can I do that?

现在我的问题是假设我已经在窗口上创建了大约 25 个文本框的 5 行。我专注于第 3 行的文本框之一,并键入一些内容来触发它适当的 KeyDown 事件。在此 keydown 事件中,我需要导致此事件的所有文本框的名称。我怎样才能做到这一点?

This, being done, will also help me to access all the other textBoxes of that row as I know the nomenclature using which they are named. Please help.

这样做后,也将帮助我访问该行的所有其他文本框,因为我知道它们被命名的命名法。请帮忙。

采纳答案by Viv

You can try something like:

您可以尝试以下操作:

Note we also set the Nameproperty along with the FrameworkContentElement.RegisterNamefunction.

请注意,我们还将该Name属性与FrameworkContentElement.RegisterName函数一起设置。

var box = new TextBox();
var itemName = "Unique Identifier";  // Change this to your unique name per box
this.RegisterName(itemName, box);
box.Name = itemName;
box.KeyDown += (sender, args) => {
  var textBox = sender as TextBox;
  if (textBox != null)
    MessageBox.Show(textBox.Name);  // Would show "Unique Identifier"
};

回答by Shafqat Masood

hi please use this event for the TextBox

嗨,请将此事件用于 TextBox

TextBox_PreviewKeyDown(object sender, KeyEventArgs e)

and get the id of the textboxes use sender parameter with combination with the Tag.

并使用 sender 参数与 Tag 组合获取文本框的 id。

 i.e.     TextBox textbox = (TextBox)sender;