[英]How do I access a control from a built string(control name)?
問題代碼:
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。
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的評論中,該帖子提到您可以將所有元素添加到列表中,並在需要時循環/ foreach:
List<TextBox> textBoxesToEdit = new List<TextBox>(){tbposition1, tbposition2 /*so on*/};
foreach (TextBox textbox in textBoxesToEdit)
{
//do stuff
}
FindName()
應該可以幫助您 ,但是請注意,如果在最初創建控件后添加它們,則可能必須在創建每個控件時對其進行注冊 。
與您對我的問題的回答一致,我將tdPositionXYZ存儲在數組或列表中,然后執行此操作,而不是全部代碼:
Dispatcher.Invoke(() => {
tbPositionArray[dealerPosition()].Text = dealerPosition().ToString();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.