0

我想创建 MarkupExtension 来为按钮单击事件提供支持。我在这里有一篇 PreviewKeyDown 的文章。我试图为 Click 修改它,但无法这样做,因为它会引发异常

请建议如何实施。

4

1 回答 1

1

看起来它试图转换MethodInfoEventInfo,返回的目标属性可能是 aMethodInfo或者EventInfo您必须在创建委托之前检查它

试试这个

    public class Call : MarkupExtension
    {
        public string ActionName { get; set; }
        public Call(string actionName) { ActionName = actionName; }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            IProvideValueTarget targetProvider = serviceProvider
                .GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
            if (targetProvider == null)
                throw new InvalidOperationException(@"The CallAction extension 
                can't retrieved the IProvideValueTarget service.");

            var target = targetProvider.TargetObject as FrameworkElement;
            if (target == null)
                throw new InvalidOperationException(@"The CallAction extension 
                    can only be used on a FrameworkElement.");

            if (targetProvider.TargetProperty is MethodInfo)
            {
                var targetEventAddMethod = targetProvider.TargetProperty as MethodInfo;
                if (targetEventAddMethod != null)
                {
                    ParameterInfo[] pars = targetEventAddMethod.GetParameters();
                    Type delegateType = pars[1].ParameterType;
                    MethodInfo methodInfo = this.GetType().GetMethod("MyProxyHandler", BindingFlags.NonPublic | BindingFlags.Instance);
                    return Delegate.CreateDelegate(delegateType, this, methodInfo); ;
                }

            }
            else if (targetProvider.TargetProperty is EventInfo)
            {
                var targetEventInfo = targetProvider.TargetProperty as EventInfo;
                if (targetEventInfo != null)
                {
                    Type delegateType = targetEventInfo.EventHandlerType;
                    MethodInfo methodInfo = this.GetType().GetMethod("MyProxyHandler", BindingFlags.NonPublic | BindingFlags.Instance);
                    return Delegate.CreateDelegate(delegateType, this, methodInfo);
                }
            }
            return null;
        }

        void MyProxyHandler(object sender, EventArgs e)
        {
            FrameworkElement target = sender as FrameworkElement;
            if (target == null) return;
            var dataContext = target.DataContext;
            if (dataContext == null) return;

            //get the method on the datacontext from its name
            MethodInfo methodInfo = dataContext.GetType()
                .GetMethod(ActionName, BindingFlags.Public | BindingFlags.Instance);
            methodInfo.Invoke(dataContext, null);
        }
    }
于 2013-01-08T03:47:29.600 回答