如何通过代码添加eventsetter

时间:2012-05-09 02:35:57

标签: c# wpf delegates event-handling eventsetter

一个完整的例子

    public delegate void mouseup_delegate(object obj, MouseButtonEventArgs args);

    constructor()
    {
        TextBlock text_block = new TextBlock() { Text = "aa" };
        Style style = new Style();
        //style.Setters.Add(new EventSetter(){Event=TextBlock.MouseUpEvent, Handler=new mouseup_delegate(this.textblockClicked)});
        style.Setters.Add(new EventSetter(TextBlock.MouseUpEvent, new mouseup_delegate(this.textblockClicked)));
        text_block.Style = style;
    }

    public void textblockClicked(object sender, MouseButtonEventArgs args)
    {
        MessageBox.Show("mouse up");
    }

但是当我运行应用程序时,会出现异常:处理程序类型无效

这段代码出了什么问题?

1 个答案:

答案 0 :(得分:7)

EventSetter期望您提供的代表是MouseButtonEventHandler,而不是mouseup_delegate