【问题标题】:C++/CLI: Change Property of a dynamically added control at RuntimeC++/CLI:在运行时更改动态添加的控件的属性
【发布时间】:2020-04-04 21:34:24
【问题描述】:

我已经看到它在 C# 中工作,但在 Visual C++ 2015 中却没有

System::Windows::Forms::Label^ mylabel= (gcnew System::Windows::Forms::Label());
mylabel->Name = L"pole";
mylabel->Text = "Hello";
this->Controls->Add(mylabel);

请注意,mylabel 在这里是一个临时变量。 现在代码适用于 C#

Control cc = this.Controls.Find("pole", true).First();
cc.text="New";

我已经尝试过了,因为没有 .First() 或 ->first(),

Control^ x = this->Controls->Find(L"pole", true);

肯定会显示错误

`cli::array<System::Windows::Forms::Control ^, 1> ^" cannot be used to initialize an entity of type "System::Windows::Forms::Control ^`"

如何在运行时将该对象作为控件?

【问题讨论】:

  • array&lt;Control^&gt;^ x = .... Winforms 不保证控件名称是唯一的,因此您会得到一个数组。希望它是数组中的第一个元素,x[0]。

标签: visual-studio visual-c++ c++-cli


【解决方案1】:

Find 方法返回一个数组。在您的 C# 示例中,您调用 First() 它返回数组中的第一项(返回对控件的引用)。在 C++ 示例中,您不调用 First() 或执行任何操作来检索单个项目。这就是为什么错误消息表明您无法将数组(注意 cli::array 错误)转换为 Control 引用的原因。

【讨论】:

  • 实际上那里没有 first() 。所以我很困惑我可以在那里使用什么替代方案。
  • 首先是扩展方法。在 C# 中调用扩展方法使用与常规方法调用相同的语法。在 C++ 中(我认为)你需要像任何其他静态方法一样显式调用扩展方法(即 System.Linq.Enumerable.First(this->Controls->Find(L"pole", true));。或者你也许可以只使用 this->Controls->Find(L"pole", true)[0]; 但自从我使用托管 C++ 以来已经有一段时间了,我不确定。
猜你喜欢
  • 1970-01-01
  • 2013-03-27
  • 2017-04-22
  • 1970-01-01
  • 1970-01-01
  • 2013-06-29
  • 1970-01-01
  • 2019-04-04
  • 1970-01-01
相关资源
最近更新 更多