我在一个单独的类中提供了一些动态创建元素的方法。动态创建该元素不是问题,而是路由事件。
我认为“路径”(例如namespace.class.method)是通过创建方法中的参数提交的。
但是到目前为止,我还无法附加这样的事件监听器。我使用Google和StackOverflow进行了许多研究,但没有成功。
我发布以下方法的源代码。 我的最后一次尝试是if节中“ EventHandler”的代码不为空。 我的想法可能会起作用,还是只能在正在初始化应用程序的主类中附加事件处理程序。
static public WrapPanel comboBox(string Name, List<string> Items, bool MultiSelection = false, string EventHandler="",string Label="", int Width = 0)
{
WrapPanel lPanel = new WrapPanel();
lPanel.Name = "stPanel_" + Name;
if (Label != "")
{
Label lLabel = new Label();
lLabel.Content = Label;
lPanel.Children.Add(lLabel);
if (Width != 0)
{
lPanel.Width = Width;
}
}
dynamic lComboBox;
if (MultiSelection)
{
lComboBox = new ComboBoxAdv();
lComboBox.AllowMultiSelect = true;
}
else lComboBox = new ComboBox();
lComboBox.Name = Name;
foreach (string Item in Items) lComboBox.Items.Add(Item);
lPanel.Children.Add(lComboBox);
ComboBox dkaf = new ComboBox();
if (EventHandler != "")
{
string lClass = "";
string lMethod = EventHandler.Split('.').Last();
for (int lCounter = 0; lCounter < EventHandler.Split('.').Length - 1; lCounter++)
lClass += EventHandler.Split('.')[lCounter] + ".";
lClass = lClass.Substring(0, lClass.Length - 1);
object dynamicObject;
Type objectType = Type.GetType(lClass);
dynamicObject = Activator.CreateInstance(objectType);
System.Reflection.MethodInfo method = objectType.GetMethod(lMethod);
//method.Invoke(dynamicObject, new object[] { });
lComboBox.Click += new RoutedEventHandler(method);
}
return lPanel;
}
最好的问候 克里斯