如果我正確理解你的問題,這可能與一些幫助來完成Reflection ...
首先在您的cs文件的頂部添加一個:using System.Reflection;
。
因爲我不知道,如果你使用WPF或的WinForms - 這裏有兩個例子...
WPF:
您可以使用此版本SetParam的:
private void SetParam(string name, string property, dynamic value)
{
// Find the object based on it's name
object target = this.FindName(name);
if (target != null)
{
// Find the correct property
Type type = target.GetType();
PropertyInfo prop = type.GetProperty(property);
// Change the value of the property
prop.SetValue(target, value);
}
}
用法:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
SetParam("textbox", "Text", "Hello");
凡textbox
聲明如下:
<TextBox x:Name="textbox" />
對於的WinForms只是改變SetParam這樣:
private void SetParam(string name, string property, dynamic value)
{
// Find the object based on it's name
object target = this.Controls.Cast<Control>().FirstOrDefault(c => c.Name == name);
if (target != null)
{
// Find the correct property
Type type = target.GetType();
PropertyInfo prop = type.GetProperty(property);
// Change the value of the property
prop.SetValue(target, value);
}
}
這是在C#代碼「元件」的含義是什麼? – 2013-03-12 22:23:21
如果在將值傳遞給單獨的方法時知道元素和屬性,爲什麼不能在代碼隱藏中執行'textbox1.Text = value;'而不是調用單獨的方法來設置值。 – 2013-03-12 22:26:54
我需要使用三個已知字符串的方法設置屬性值:元素(ElementID,如texbox1),屬性(如文本)和值。 – 2013-03-12 22:35:54