2

コードにボタンのリストを追加し、それらの mouseleave イベントをサブスクライブしています。匿名関数を使用してイベントにサブスクライブするボタンごとに、問題は、アプリを実行すると、すべてのボタンが最後の匿名関数にサブスクライブされることです。これがコードです。自分で説明したことを願っています。

var modules = ModulesSC.GetAllMoudules();
var imageSet = ModulesSC.GetModuleImageSet();

foreach (var module in modules)
{
    var btn = new Button();
    btn.SetResourceReference(Control.TemplateProperty, "SideMenuButton");
    btn.Content = module.Title;
    btn.MouseEnter += (s, e) => { ShowInfo(module.Description); };
    btn.MouseLeave += (s, e) => { HideInfo(); };
    ModuleButtons.Children.Add(btn);
}

protected void HideInfo()
{
   DescriptionLabel.Visibility = Visibility.Collapsed;
   DescriptionText.Text = string.Empty;
}

protected void ShowInfo(string description)
{
   DescriptionLabel.Visibility = Visibility.Visible;
   DescriptionText.Text = description;
}

アプリを実行すると、すべて「module.Description」で showInfo が呼び出されます

ありがとう -アレハンドロ

4

2 に答える 2

3

これは、C# がループ変数を閉じる方法に問題があります。内部 に一時変数を追加し、それを匿名メソッドで使用します。

foreach (var module in modules)
{
    var theModule = module;  // local variable
    var btn = new Button();
    btn.SetResourceReference(Control.TemplateProperty, "SideMenuButton");
    btn.Content = theModule.Title;  // *** use local variable
    btn.MouseEnter += (s, e) => { ShowInfo(theModule.Description); };  // *** use local variable
    btn.MouseLeave += (s, e) => { HideInfo(); };
    ModuleButtons.Children.Add(btn);
}

ループ変数「module」の代わりにローカル変数「theModule」を使用していることに注意してください。

于 2009-11-26T22:50:25.587 に答える
0

これが何の言語かはわかりませんが、C# である可能性があります。

そうである場合、ボタン クリック イベント ハンドラーには、「オブジェクト センダー」と関数への EventArgs 引数が必要です。

「オブジェクト送信者」は、どのボタンが押されたかを知ることができます。

Button pressedButton = (Button)sender;
if(pressedButton.Text.Equals("Button 1")
    doStuff();

これは単なる例です。テキスト フィールドを比較するよりも、それがどのボタンであるかを判断するためのより良い方法がありますが、アイデアはわかります。

于 2009-11-26T22:49:55.927 に答える