c# - WPF 为什么 methodInfo = object.GetType().GetMethod ("SelectionChanged") ..... 返回空值?

标签 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”和更多标志,但结果始终为空 任何人都可以帮助我并指出我的错误在哪里 提前谢谢你

最佳答案

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

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

相关文章:

c# - WPF 应用程序无法启动

c# - TextBox 绑定(bind)到 double 并输入小于 -1 的负数时出现问题

c# - WPF双向数据绑定(bind)列表框在WPF中建模无法获取选定值

Wpf 按钮数据触发

wpf - WPF 中的下划线标签,使用样式

c# - COM 接口(interface)中函数返回中的 Guid 对象

c# - 外部请求的身份验证 - 如何在 SOAP header 中传递用户凭据?

c# - DLL 的 app.config 中的 ConnectionString 为空

c# - `Dictionary<TKey, TValue>.KeyCollection` 是否实现了 `IReadOnlyCollection`?

wpf - 如何将许多图像拼接在一起以提供像 Photosynth 一样的 3D 沉浸式体验?