如何从生成的字符串(控件名称)访问控件

本文关键字:控件 访问 字符串 | 更新日期: 2023-09-27 18:36:07

>问题代码:

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 的评论中,这篇文章提到您可以将所有元素添加到列表中,并在您想要处理它时循环/为它:

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