[英]Accessing variables dynamically in C#
I have tons of Buttons named like this x0y1
我有很多这样命名的按钮x0y1
How do I access the variable name dynamically so I could loop all names by xiy1
or so. 如何动态访问变量名称,以便可以按xiy1
左右循环所有名称。
in PHP it would be like ${"myString" . $randomvar}
在PHP中,它就像${"myString" . $randomvar}
${"myString" . $randomvar}
I can't use a list or array because the the button already exist defined through the xaml 我不能使用列表或数组,因为通过xaml定义的按钮已经存在
You can use: 您可以使用:
var textbox =
this.Controls.OfType<TextBox>().Where(txb => txb.Name == "myString").FirstOrDefault();
This assumes you are in the context of your form ( this.Controls
). 假设您处于表单上下文( this.Controls
)中。
And of course, don't forget to add using System.Linq;
当然,不要忘记using System.Linq;
添加using System.Linq;
... ...
You can get all the textbox using this method 您可以使用此方法获取所有文本框
void AllTextBox(System.Windows.Forms.Control.ControlCollection ctrls)
{
foreach (Control ctrl in ctrls)
{
if (ctrl is TextBox)
{
if (ctrl.Name == "textBox1")
{
// do your stuf with textbox
}
}
}
}
You can create function that return control by name : 您可以创建按名称返回控件的函数:
Control GetControlByName(string Name)
{
foreach(Control control in this.Controls)
if(c.Name == Name) return control ;
return null;
}
or Function with a specific control like that : 或具有以下特定控件的功能:
Button GetButtonByName(string Name)
{
foreach (Control c in this.Controls.OfType<Button>())
if (c.Name == Name) return c;
return null;
}
For wpf project... 对于WPF项目...
Let's say you have a grid named MyGrid
and there's lot of buttons on it. 假设您有一个名为MyGrid
的网格, MyGrid
有很多按钮。 You want to refer to the button named x0y1
: 您要引用名为x0y1
的按钮:
var btn = MyGrid.Children.OfType<Button>().Where(x=>x.Name=="x0y1");
Note: above code should work for flat structure (one level deep only). 注意:以上代码应适用于平面结构(仅一层深度)。
You can achieve the same by using code provided in this thread: How can I find WPF controls by name or type? 您可以通过使用此线程中提供的代码来实现相同的目的: 如何通过名称或类型查找WPF控件?
Just call FindName("elementName"). 只需调用FindName(“ elementName”)。 FindName searches through all child elements of a FrameworkElement. FindName搜索FrameworkElement的所有子元素。 To access any button by its name as string in a window, call the FindName() method of the window ! 要在窗口中按其名称作为字符串访问任何按钮,请调用窗口的FindName()方法!
If your code is in a class inheriting from Window, just use: 如果您的代码在继承自Window的类中,则只需使用:
Button button = (Button)FindName("xiy1");
If you write the code in a class not inheriting from Window but FrameworkElement, which is unlikely, use: 如果您在不继承自Window但继承自FrameworkElement的类中编写代码(不太可能),请使用:
Window window = Window.GetWindow(this);
Button button = (Button)window.FindName("xiy1");
Check the MSDN documentation about Namescopes for more information about limitations. 有关检查MSDN文档名称范围有关限制的详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.