我正在尝试创建一个WPF应用程序,允许用户创建一个动态加载了一些xaml文件的自定义gui。
这需要两个文件:
包含gui元素的主要xaml文件
<Grid>
<Button Name="button1" Height="82" Width="132">Button Text</Button>
<TextBlock Text="Text Data"/>
</Grid>
以及包含事件的事件文件:
<Events>
<Event Object="button1" Event="Click" File="button1OnClick"/>
</Events>
我正确加载文件并显示gui,但不会触发事件(在此示例中为按钮单击事件)。我用这段代码(以及它的一些变种)尝试了它:
/*
scroll = parent object of the custom gui (ScrollViewer)
events = List of the events in the events file
evnt.Event == "Click"
evnt.ObjectName == "button1"
evnt.File == "button1OnClick"
*/
List<DependencyObject> childs = scroll.GetLogicalChilds();
foreach (DependencyObject control in childs)
{
Control c = null;
if(control is DependencyObject)
c = control as Control;
if (c == null)
continue;
foreach(PluginEvent evnt in events)
{
if (evnt.ObjectName == c.Name) //button1 == button1
{
RoutedEvent routedEvent = EventManager.RegisterRoutedEvent(
evnt.Event,
RoutingStrategy.Bubble,
typeof(RoutedEventHandler),
c.GetType());
Action handler = () => Lua.DoFile(evnt.File + ".lua");
c.AddHandler(routedEvent, handler);
}
}
}
在此示例中,当我单击名为button1OnClick.lua
的按钮但我收到错误时,我尝试运行button1
文件
处理程序类型不匹配。
我不知道如何解决这个问题。有人可以解释一下在触发事件时如何运行lua文件吗?
目标是在触发事件时运行在事件文件中声明的文件。
EDIT1:
我用这段代码修复了异常
RoutedEvent routedEvent = EventManager.RegisterRoutedEvent(evnt.Event, RoutingStrategy.Bubble, typeof(RoutedEventHandler), c.GetType());
RoutedEventHandler handler = (s, a) => Lua.DoFile(evnt.File + ".lua");
c.AddHandler(routedEvent, handler);
但如果单击按钮
则不会触发答案 0 :(得分:0)
更改此
Action handler = () => Lua.DoFile(evnt.File + ".lua");
c.AddHandler(routedEvent, handler);
更多适当的事件处理程序
c.AddHandler(routedEvent, (delegate)(s, o) => Lua.DoFile(evnt.File + ".lua")); // not sure
根据您的评论(^^):
Action<object,RoutedEventHandler> handler = (s, o) => Lua.DoFile(evnt.File + ".lua");
c.AddHandler(routedEvent, handler);