4

典型的な電卓のような win フォーム UI があります。当然、数字ボタン (0 ~ 9) ごとに同じロジックを書き直したくありません。どのボタンがクリックされたかを知りたいので、そのテキスト プロパティに基づいて計算を実行できます。コードの再利用を促進するために、ボタン オブジェクトをパラメーターとして受け入れるメソッドを作成する必要がありますか? より良い方法はありますか?在職中の Win Form アプリ開発者がこれをどのように処理するかを聞きたいです。ロジックを UI から遠ざけようとしています。

ありがとう!

4

2 に答える 2

7

イベント ハンドラの典型的なシグネチャはvoid EventHandler(object sender, EventArgs e). 重要な部分はobject sender. これは、イベントを発生させたオブジェクトです。のクリック イベントの場合Button、送信者はその になりますButton

void digitButton_Click(object sender, EventArgs e)
{
    Button ButtonThatWasPushed = (Button)sender;
    string ButtonText = ButtonThatWasPushed.Text; //the button's Text
    //do something

    //If you store the button's numeric value in it's Tag property
    //things become even easier.
    int ButtonValue = (int)ButtonThatWasPushed.Tag;
}
于 2009-01-17T20:04:39.397 に答える
3

イベント ハンドラーを指定する場合、同じ関数を登録して複数のイベントを処理できます (VS.Net の場合は、プロパティに移動し、イベント セクション (稲妻ボタン) を選択し、[クリック] のドロップダウンをクリックします)。このようにして、すべてのボタンを処理する 1 つのイベント ハンドラー関数を記述します。

例 (C#) ボタンの作成とイベントの登録をコードで行う場合:

public void digitButtons_Click(object sender, EventArgs eventArgs) {
    if(sender is Button) {
        string digit = (sender as Button).Text;
        // TODO: do magic
    }
}

public void createButtons() {
    for(int i = 0; i < 10; i++) {
        Button button = new Button();
        button.Text = i.ToString();
        button.Click += digitButtons_Click;
        // TODO: add button to Form
    }
}
于 2009-01-17T19:46:13.413 に答える