为了使这更容易,我将展示我的代码,然后解释我试图做什么。
CODE+EXPLANATION:
首先,当用户单击一个按钮时,它将带有附加信息转到Other。
private void button1_Click(object sender, EventArgs e)
=> Other("https://pastebin.com/raw/something", "Program1", "A");
private void button2_Click(object sender, EventArgs e)
=> Other("https://pastebin.com/raw/something", "Program2", "B");其次,我下载了一个XML文档并从中提取相关信息:
private void Other(string UniversalURL, string ProductNAME, string ProductCHANNEL)
{
//Download the Doc
XmlDocument document = new XmlDocument();
document.Load(UniversalURL);
string expandedEnvString = Environment.ExpandEnvironmentVariables("%USERPROFILE%/AppData/Local/Temp/zADU.xml");
File.WriteAllText(expandedEnvString, document.InnerXml);
XmlDocument doc = new XmlDocument();
doc.Load(expandedEnvString);
//Get the needed Nodes
XmlNode nodeXMLProgram = doc.DocumentElement.SelectSingleNode($"/{ProductNAME}");
string XMLProgram = nodeXMLProgram.InnerText;
// Creation of Button Here
}目标:我想要做的是使用字符串,从中提取,并将它们用作创建按钮的变量,类似于这样:
Button Program(XMLProgram) = new Button();
Program(XMLProgram).Height = 22;
Program(XMLProgram).Width = 122;
Program(XMLProgram).BackColor = Color.FromArgb(230, 230, 230);
Program(XMLProgram).ForeColor = Color.Black;
Program(XMLProgram).Name = "DynamicButton";
Program(XMLProgram).Click += new EventHandler(ProgramProgram(XMLProgram)_Click);
Program(XMLProgram).BringToFront();
Controls.Add(ProgramProgram(XMLProgram));我能做到吗?我会很感激你的帮助!对不起,标题混淆了,我不知道该怎么正确地表达它。
发布于 2019-05-10 04:55:42
您可以使用反射来查找和设置正在反序列化的对象的属性,前提是您有一个格式正确的XML文件。
通过XDocument或XmlDocument读取XML文件,从中提取需要创建的控件类型(按钮、文本框等),还提取要从XML中设置的属性名称以及要将其设置为的值。然后创建上述控件类型的实例,并使用如下代码从XML中遍历属性列表,并在实例中设置它们:
// New instance of the control (read the type from the XML and create accordingly)
var ctrlInstance = new Button();
// Get a reference to the type of the control created.
var ctrlType = ctrlInstance.GetType();
// Dictionary to contain property names and values to set (read from XML)
var properties = new Dictionary<string, object>();
foreach (var xmlProp in properties)
{
// Get a reference to the actual property in the type
var prop = ctrlType.GetProperty(xmlProp.Key);
if (prop != null && prop.CanWrite)
{
// If the property is writable set its value on the instance you created
// Note that you have to make sure the value is of the correct type
prop.SetValue(ctrlInstance, xmlProp.Value, null);
}
}如果您打算以这种方式创建整个程序,包括代码,您将不得不使用Roslyn在运行时编译您的代码,这在实践中可能有些复杂。在这种情况下,您不需要XML文件,只需将所有代码放入源文件并编译它,然后在自己的程序中实例化它。如果您只想以编程方式创建表单并处理其父窗体中的事件,这将很好。
https://stackoverflow.com/questions/56070385
复制相似问题