【问题标题】:Changing multiple control properties at once一次更改多个控件属性
【发布时间】:2012-07-02 09:53:09
【问题描述】:

我需要更改大量控件中的一堆属性。我很难让它工作。我在正确的轨道上吗?

foreach(var c in this.Controls.OfType<Label>())
            {
                c.Text = "test";
            }

发生的事情是 var c 只是创建一个新对象而不是编辑现有对象。如何访问真正的控件?

【问题讨论】:

  • 您只是在循环通过一组控件-“c”实际上是对该控件的引用-您正在编辑现有控件。您使用的是什么演示技​​术? WinForms、WPF 还是 ASP.Net?
  • 我正在制作一个 Windows 应用
  • 这是一个常见问题 - 请参阅此答案,例如:stackoverflow.com/a/1467980/1073107stackoverflow.com/questions/1788490/… - 不过,我假设您的意思是 Windows 窗体。
  • stackoverflow.com/a/1788757/1073107 也非常非常有用,应该完全满足您的需求。
  • 好的,我已经在我的代码中工作了。它实际上是由其他地方的空对象引起的,这让我怀疑它没有工作......对不起。

标签: c#


【解决方案1】:

尝试以下方法:

foreach(var c in this.Controls)
{
    var label = c as Label;
    if(label != null) label.Text = "test";
}

【讨论】:

    【解决方案2】:

    你可以试试这个

     List<Control> controls = Controls.OfType<Label>().Cast<Control>().ToList();
      foreach (Control m in controls)
      {
          m.Text = "test";
    
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-05
      • 2011-11-20
      • 1970-01-01
      • 2011-06-30
      • 2012-02-15
      • 2020-11-26
      • 1970-01-01
      相关资源
      最近更新 更多