views:

10

answers:

1

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.
+1  A: 

Thats basically how closures and loops work in c#.

Take a look at good explanation here

miensol
Ah, yes, thanks! I knew I've read about that before, yet totally forgot about it. I appreciate the link.
Dave