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

当我运行应用程序时,它们都使用 las“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);
}

注意使用局部变量“theModule”而不是循环变量“module”。

于 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 回答