【问题标题】:Programmatically adding buttons - Problem with subscription to a mouse event以编程方式添加按钮 - 订阅鼠标事件的问题
【发布时间】:2009-11-26 22:45:52
【问题描述】:

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

谢谢 -亚历杭德罗

【问题讨论】:

  • 为什么要创建匿名函数来包装定义的函数?只需首先正确定义签名以避免混淆。

标签: c# wpf events button mouseevent


【解决方案1】:

This is an issue with the way C# closes over loop variables. 添加一个临时变量inside 并在你的匿名方法中使用它:

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

【讨论】:

    【解决方案2】:

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

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

    “对象发送者”可以告诉您按下了哪个按钮。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-02
      • 1970-01-01
      • 2021-04-17
      • 1970-01-01
      • 1970-01-01
      • 2016-02-25
      • 2011-01-07
      相关资源
      最近更新 更多