当我只有字符串格式的控件名称时,如何动态添加用户控件?银光,C#
我正在努力调用不同的用户控件,并且给我的唯一数据是一个字符串,用于调用我创建的用户控件。当我知道名称时,我可以硬编码并在后面的代码中添加该控件,并以这种方式动态添加它,但是当控件的名称通过字符串传递给我时,我无法将其传递给我的usercontrol 对象并使其不为空...
这是我的代码:
string userControlName = "ReportFilterOptions";
Type type = this.GetType();
Assembly assembly = type.Assembly;
UserControl c = (UserControl)assembly.CreateInstance(type.FullName + "." + userControlName);
gridReport.Children.Clear();
gridReport.Children.Add(c);
I'm working on calling different user controls, and the only data that I've been given is a string in which to call the user control that I have created. When I know the name, I can hard code and add that control in the code behind and add it dynamically that way, but when the name of the control is being passed to me via a string, I'm having trouble passing that to my usercontrol object and having it not be null...
Here is my code:
string userControlName = "ReportFilterOptions";
Type type = this.GetType();
Assembly assembly = type.Assembly;
UserControl c = (UserControl)assembly.CreateInstance(type.FullName + "." + userControlName);
gridReport.Children.Clear();
gridReport.Children.Add(c);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用System.Activator.CreateInstance。
请参阅此示例。重要的部分是:
您可以通过迭代所有类型以匹配字符串来使其更加“用户友好”。
请参阅 此文件的第 54 行左右< /a> 在方法
UpdateClassList
中。Use System.Activator.CreateInstance.
See this example. The important parts are:
You could make this more "user friendly" by iterating all the types to match string.
See around line 54 of this file in method
UpdateClassList
.