WPF为什么methodInfo = object.GetType()。GetMethod(“SelectionChanged”).....返回一个空值?

时间:2010-11-08 10:48:36

标签: c# wpf

我在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 任何人都可以帮助我,并指出我的错误在哪里 我提前谢谢你

1 个答案:

答案 0 :(得分:1)

SelectionChanged是另一个事件,而不是方法;你不能把它当成一个方法,并将第一个事件调用到第二个。也许你的意思是(非公开的)OnSelectionChanged? (您需要指定BindingFlags.Instance | BindingFlags.NonPublic