我在代码中添加了一个按钮列表,并订阅了他们的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

由于 -Alejandro

有帮助吗?

解决方案

这是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。”

其他提示

我不知道这是什么语言,但它可能是C#。

如果是,按钮点击事件处理程序需要有一个“对象发送者”。和函数的EventArgs参数。

“对象发件人”可以告诉你按下了什么按钮。

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

这只是一个例子,确定哪个按钮比比较文本字段有更好的方法,但你明白了。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top