退出MenuItem永远禁用

时间:2014-02-15 01:07:50

标签: wpf caliburn.micro

我在WPF应用程序中有一个Exit菜单项。当我将项目移动到使用Caliburn Micro时,它在启动应用程序时已被禁用。

<MenuItem Header="E_xit" InputGestureText="Alt+F4"
          Command="ApplicationCommands.Close"/>

即使添加IsEnabled="True"也无效。如果删除命令Command="ApplicationCommands.Close",则启动时启用菜单项(但显然我希望关闭命令保持连接状态)。

我的猜测是必须有某种我不知道的方法或属性,或者我可能没有正确初始化主窗口?这是我的AppBootstrapper:

public class AppBootstrapper : BootstrapperBase
{
    SimpleContainer container;

    public AppBootstrapper()
    {
        Start();
    }

    protected override void Configure()
    {
        container = new SimpleContainer();

        container.Singleton<IWindowManager, WindowManager>();
        container.Singleton<IEventAggregator, EventAggregator>();
        container.PerRequest<IShell, MainWindowViewModel>();

        var currentParser = Parser.CreateTrigger;
        Parser.CreateTrigger = (target, triggerText) => ShortcutParser.CanParse(triggerText)
            ? ShortcutParser.CreateTrigger(triggerText)
            : currentParser(target, triggerText);

    }

    protected override object GetInstance(Type service, string key)
    {
        var instance = container.GetInstance(service, key);
        if (instance != null)
            return instance;

        throw new InvalidOperationException("Could not locate any instances.");
    }

    protected override IEnumerable<object> GetAllInstances(Type service)
    {
        return container.GetAllInstances(service);
    }

    protected override void BuildUp(object instance)
    {
        container.BuildUp(instance);
    }

    protected override void OnStartup(object sender, System.Windows.StartupEventArgs e)
    {
        DisplayRootViewFor<IShell>();
    }

    protected override IEnumerable<Assembly> SelectAssemblies() {
        return new[] {
            Assembly.GetExecutingAssembly()
        };
    }
}

1 个答案:

答案 0 :(得分:2)

我怀疑您没有为ApplicationCommands.Close设置CommandBinding

如果找不到CommandBinding,命令将始终从CanExecute方法返回 false。因此,要启用命令,您必须:

  • 首先,在根元素(可能在窗口处)或需要处理此命令的任何父元素处创建CommandBinding。
  • 其次,在该命令绑定中提供CanExecute处理程序,并根据您要启用此menuItem的条件在该处理程序中将e.CanExecute设置为True

小样本实现我上面所说的:

<TextBox>
  <TextBox.CommandBindings>
    <CommandBinding Command="ApplicationCommands.Close" 
                    Executed="CommandBinding_Executed" 
                    CanExecute="CommandBinding_CanExecute"/>
  </TextBox.CommandBindings>
  <TextBox.ContextMenu>
    <ContextMenu>
      <MenuItem Header="E_xit" InputGestureText="Alt+F4" 
                Command="ApplicationCommands.Close"/>
    </ContextMenu>
  </TextBox.ContextMenu>
</TextBox>

和处理程序后面的代码:

private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{

}

private void CommandBinding_CanExecute(object sender,
                                       CanExecuteRoutedEventArgs e)
{
   e.CanExecute = true; <-- Set this to true to enable bindings.
}

您可以在此处详细了解相关信息 - How to enable a CommandCommanding Overview