0

カスタム引数を渡してカスタムイベントハンドラーを動的に作成しようとしています。基本的に、クリックイベントが追加されたパネルがあります。

Panel awardButton = new Panel();
awardButton.Click += new EventHandler(PreviewAward);

PreviewAward関数にいくつかの変数を送信したいと思います。私は知っていることをすべて試しましたが、エラーしか得られませんでした。ヘルプを検索してみましたが、これが最も近いものです。

カスタム引数を持つEventHandler

私はそのコードを次のように使用してみました:

awardButton.Click += (sender, e) => PreviewAward(dtAward.Rows[0]["iconImage"].ToString());

ラムダの右側にあるものはすべて赤で下線が引かれ、「メソッド「PreviewAward」のオーバーロードは1つの引数を取ります」と示されています。(sender、e)が1つではなく合計3つの引数を作成する「iconImage」文字列とともにPreviewAwardメソッドに渡されていると思ったため、ラムダがどのように機能するかを理解していないと思います。また、メソッドに変数を追加しようとしましたが、同じエラーが発生します。方法は次のとおりです。

    private void PreviewAward(object sender, EventArgs e, string slot)
    {
        string str = ((Panel)sender).Name;
        MemoryStream ms = new MemoryStream(Utils.StrToByteArray(str));
        MemoryStream preview = new MemoryStream(Utils.ImageMerge(((System.Drawing.Image)(Avatar.Properties.Resources.resizeButtonIn)), Image.FromStream(ms), 200, 200));
        Debug.Print("Show Preview for item: " + str);
    }

ラムダの右側にある関数にマウスを合わせると、「PreviewAward」に小さなドロップダウンが表示され、メソッドスタブを作成する必要があります。それをクリックすると、次のようになります。

    private object PreviewAward(string p)
    {
        throw new NotImplementedException();
    }

特に「送信者」が含まれていないので、どうしたらよいかわかりません。同じ名前の新しい「プライベートオブジェクト」メソッドを作成するのではなく、すでに作成した「プライベートボイドプレビューアワード」メソッドを使用するという印象を受けました...私は完全に混乱しています!どんな助けでも大歓迎です!

4

1 に答える 1

1

The (sender, e) parameters aren't being passed to your PreviewAward method automatically.

They are being passed to your lambda, and in your lambda you are simply not using them, and manually calling PreviewAward with a single string parameter.

There are a few ways you could fix this, but the simplest is just to modify your lambda a bit so that it passes in the required arguments to the PreviewAward method.

awardButton.Click += (sender, e) => PreviewAward(sender, e, dtAward.Rows[0]["iconImage"].ToString());

Edit: That said, it's a bit of a strange design to have a click event handler that requires an extra parameter - it means that the signature of the method doesn't match the EventHandler signature. It might be worth rethinking the design a bit so that the third parameter is calculated inside of the method, for example.

于 2013-03-12T16:03:05.843 に答える