tags:

views:

327

answers:

1

Hello,

I am creating a menu and binding the menu items ate runtime as follows but I am not able to make it work.

I am creating the menu as follows:

  Menu menu = new Menu();      
  menu.Items.Add(new MenuItem {  Command = new PackCommand(), Header = "Pack" });
  DockPanel.SetDock(menu, Dock.Top);
  content.Children.Add(menu);

And I am implementing ICommand:

public static class PackCommand : ICommand {
  Boolean CanExecute(object parameter) {
    return true;
  }
  void Execute(object parameter) {
    Packer packer = new Packer();
    packer.Run();
  }
}
  1. I am not sure how to bind the menu item.
  2. Why CanExecute? Shouldn't it always? I only want to run packer.Run when the buttom is clicked.

I think I should implement ICommand but I am not even sure I should do this?

Could someone please help me out?

Thanks, Miguel

A: 

There are certainly cases where you want to implement CanExecute, because that's what controls the state of the button. For example, you could have a button that you don't want users to press until they've done something else. In CanExecute, you can check the state of the GUI and make sure that this happens.

If you always want the button to be clickable / executable, then return true.

As far as binding goes, in your XAML, you can specify a Command in your MenuItem element. Something like:

<MenuItem Command="PackCommand" Header="MyHeader" />

Now you still have to define your Command properly in code-behind. Here's how I've done my Commands before -- perhaps it'll help you get going in the right direction:

public class GUICommands
{
    private static RoutedUICommand start;

    static GUICommands()
    {
        start = new RoutedUICommand( "Start", "Start", typeof(GUICommands));
    }

    public static RoutedUICommand Start
    {
        get { return start; }
    }
}

FYI, in my XAML, I would have bound my command like this:

<MenuItem Command="my:GUICommands.Start" />

where "my" is the xmlns I have declared in my XAML that corresponds to the namespace that GUICommands is a part of.

Dave