简体   繁体   中英

How do I access a control from a built string(control name)?

Problem code:

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;
    }
}

Using 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(); });

From Complexity's comment though, the post mentions that you can add all of your elements into the list and loop / foreach that when you want to work on it:

List<TextBox> textBoxesToEdit = new List<TextBox>(){tbposition1, tbposition2 /*so on*/};

foreach (TextBox textbox in textBoxesToEdit)
{
  //do stuff
}

FindName() 应该可以帮助您 ,但是请注意,如果在最初创建控件后添加它们可能必须在创建每个控件时对其进行注册

In line with your answer to my quetion I would store my tdPositionXYZ in an array or List and do this instead of all of your code:

Dispatcher.Invoke(() => {
    tbPositionArray[dealerPosition()].Text = dealerPosition().ToString();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM