如何在WPF 4.5中为按钮单击事件制作标记扩展?

时间:2013-01-08 03:26:28

标签: c# .net wpf .net-4.5

我想创建MarkupExtension以支持Button click事件。我有一篇关于PreviewKeyDown here的文章。我尝试将其修改为Click但无法执行此操作,因为它会抛出异常

请建议如何实施。

1 个答案:

答案 0 :(得分:1)

看起来它试图将MethodInfo转换为EventInfo,返回的目标属性可能是MethodInfoEventInfo,您必须在创建委托之前检查此属性< / p>

试试这个

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