问题代码:
for (int i = 0; i <= numberOfPlayers - 1; i++)
{
if (i == dealerPosition())
{
StringBuilder sb = new StringBuilder();
// e.g. outputs "tbPosition1"
sb.Append("tbPosition").Append(dealerPosition().ToString());
// The following line of code does not work as sb is a string containing
// "thPosition1", not my controller tbPosition1. How do I fix this?
Dispatcher.Invoke(() => { (sb.Text = dealerPosition().ToString(); });
break;
}
}
使用C#,WPF,Visual Studio。
答案 0 :(得分:1)
sb.Append("tbPosition").Append(dealerPosition().ToString());
// The following line of code does not work as sb is a string containing
// "thPosition1", not my controller tbPosition1. How do I fix this?
Dispatcher.Invoke(() => { ((this.FindName(sb.ToString()) as TextBox).Text = dealerPosition().ToString(); });
从Complexity的评论中,post提到您可以将所有元素添加到列表中,并在您想要处理它时循环/预测:
List<TextBox> textBoxesToEdit = new List<TextBox>(){tbposition1, tbposition2 /*so on*/};
foreach (TextBox textbox in textBoxesToEdit)
{
//do stuff
}
答案 1 :(得分:0)
FindName()
should help you with this,但请注意,如果在最初创建控件后添加它们,则可能必须may have to register each control as you create it。
答案 2 :(得分:0)
根据你对我的排名的回答,我会将我的tdPositionXYZ存储在一个数组或列表中,而不是使用所有代码来执行此操作:
Dispatcher.Invoke(() => {
tbPositionArray[dealerPosition()].Text = dealerPosition().ToString();
});