how to add eventsetter by code

7.2k Views Asked by At

A complete example

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

But when I run the app, an exception is thown: Handler type is not valid

what's wrong with this code?

1

There are 1 best solutions below

1
On BEST ANSWER

EventSetter expects the delegate you provide to be a MouseButtonEventHandler, not a mouseup_delegate.