简体   繁体   中英

WPF why methodInfo = object.GetType().GetMethod(“SelectionChanged”) … return a null value?

I have a form in wpf , at runtime in the Load event add the following controls from XAML string

// 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);
}

then add a Canvas a dataGrid control

// 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);
}

I must now add events to DataGrid control , but the method GetMethod always returns 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);

of course I tried with the method "SelectionChanged" and more flag but the result is always null anyone can help me and indicate where is my mistake I thank you in advance

SelectionChanged is another event, not a method; you can't treat it like a method and have the first event call into the second. Perhaps you mean the (non-public) OnSelectionChanged ? (you would need to specify BindingFlags.Instance | BindingFlags.NonPublic )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM