0

I think this is my overall .NET inexperience speaking here, but I cannot figure out why this is happening to me.

My Model ImportManys an interface called ISystemSetupEditor, and in this case I have a couple of parts that Export that interface.

In the application's ViewModel, I have a method that creates a menu, and iterates over the IEnumerable<ISystemSetupEditor> to populate the menu items, like so:

private ObservableCollection<WPFMenuItem> CreateSystemSetupItems()
{
    ObservableCollection<WPFMenuItem> menu = new ObservableCollection<WPFMenuItem>();

    foreach(ISystemSetupEditor editor in _model.SystemSetupEditors) {
        WPFMenuItem menuitem = new WPFMenuItem( editor.GetName());
        menuitem.Command = new RelayCommand( () => editor.ShowTool());
        menu.Add( menuitem);
    }

    return menu;
}

The problem is, when I click on any menu item, the ShowTool() for the last-enumerated ISystemSetupEditor-derived object always gets called. It's as if the same reference is being stored by each RelayCommand.

I was hoping that someone could:

  • explain why this is happening, or at least give me a keyword so I can look it up and figure it out on my own
  • present possible solutions -- the only one I've come up with so far is to manage a separate Dictionary, where T,U would be able to resolve to the correct library so the right function can get called later on.
Dave
  • 14,618
  • 13
  • 91
  • 145
  • It might be that you should pass in a helper method that takes e.g the name of the editor. That helper method can then search for the correct editor and call ShowTool() on it – Dave Archer Jun 24 '10 at 17:44
  • @David: thanks, I will likely have to give that a try... it sounds basically like what I was proposing above with the Dictionary that keeps track of the association between a setup tool and possibly, its name. – Dave Jun 24 '10 at 17:49

1 Answers1

1

Thats basically how closures and loops work in c#.

Take a look at good explanation here

Community
  • 1
  • 1
miensol
  • 39,733
  • 7
  • 116
  • 112
  • Ah, yes, thanks! I knew I've read about that before, yet totally forgot about it. I appreciate the link. – Dave Jun 24 '10 at 19:04