[英]Best way to identify a WPF control?
I apologize for the vague title. 对于模糊的标题,我深表歉意。 I'm trying to find a better way to do this: 我正在尝试找到一种更好的方法来做到这一点:
public void DoSomething(Textbox tb)
{
switch(tb.Name)
{
case "tbOne":
// Do something
break;
case "tbTwo":
// Do something else
break;
}
}
I don't like hardcoding the textbox names because they can change and break my code. 我不喜欢对文本框名称进行硬编码,因为它们会更改和破坏我的代码。 Any ideas on how to better do this? 关于如何更好地做到这一点的任何想法?
You can use the Tag property of the Textboxes, it can hold anything (any object, string, int,...) you want. 您可以使用文本框的Tag属性,该属性可以容纳所需的任何内容(任何对象,字符串,整数,...)。
In many cases you could find that what you are doing is not needed. 在许多情况下,您可能会发现您不需要做什么。 If you add to your question what it is you are trying to accomplish you might get better suggestions. 如果您要回答的问题是什么,那么您可能会得到更好的建议。
You don't really need to hard code it, just do this instead of what you have: 您实际上不需要硬编码,只需执行此操作即可,而不是您拥有的功能:
public void DoSomething(Textbox tb)
{
if(tb == tbOne)
{
}
else if (tb == tbTwo)
{
}
}
That way if they change you'll get a compile time exception =). 这样,如果它们更改,您将获得编译时异常=)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.