我在wpf中有一个表单,在运行时在Load事件中从XAML字符串添加以下控件

// load Canvas
sXAML = "<Canvas  xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'";
sXAML += " Height=\"Auto\" Name=\"canvasMain\" Width=\"Auto\">";
sXAML += " </Canvas>";

XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(sXAML);
XmlTextReader xmlReader = new XmlTextReader(new StringReader(xdoc.OuterXml));
object obj = XamlReader.Load(xmlReader);

if (obj != null)
{
 Canvas cnv = obj as Canvas;
 this.AddChild(cnv);
        this.RegisterName(cnv.Name, cnv);
}


然后添加一个Canvas一个dataGrid控件

// load dataGrid
sXAML = "<DataGrid xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'";
sXAML += " AutoGenerateColumns=\"True\" Height=\"207\" HorizontalAlignment=\"Left\" Margin=\"140,6,0,0\" Name=\"dtgListServer\" VerticalAlignment=\"Top\" Width=\"751\" AlternatingRowBackground=\"LightCyan\">";
sXAML += "</DataGrid>";

XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(sXAML);
XmlTextReader xmlReader = new XmlTextReader(new StringReader(xdoc.OuterXml));
object obj = XamlReader.Load(xmlReader);

if (obj != null)
{
 DataGrid dtg = obj as DataGrid;
        cnv.Children.Add(dtg);
        cnv.RegisterName(dtg.Name, dtg);
}


我现在必须将事件添加到DataGrid控件,但是方法GetMethod始终返回null

EventInfo ei = dtg.GetType().GetEvent(eventname);
MethodInfo mi = dtg.GetType().GetMethod(methodname, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
Delegate del = Delegate.CreateDelegate(ei.EventHandlerType, this, mi);
ei.AddEventHandler(dtg, del);


当然,我尝试使用方法“ SelectionChanged”和更多标志,但结果始终为null
任何人都可以帮助我并指出我的错误在哪里
我提前谢谢你

最佳答案

SelectionChanged是另一个事件,不是方法。您不能将其视为方法,而将第一个事件调用到第二个中。也许您是说(非公开)OnSelectionChanged? (您需要指定BindingFlags.Instance | BindingFlags.NonPublic

关于c# - WPF为什么methodInfo = object.GetType()。GetMethod(“SelectionChanged”)…返回空值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4123136/

10-12 04:33