代码之家  ›  专栏  ›  技术社区  ›  DotNetRussell

命令绑定在弹出式菜单或弹出式菜单中不工作

  •  2
  • DotNetRussell  · 技术社区  · 7 年前

    所以我的其他按钮都以相同的方式装配,在相同的视图和视图模型中,工作正常。

    然而,这个恰好在上下文菜单中的,却没有。即使当我将命令绑定更改为我知道不存在的东西时,也没有任何绑定表达式错误,我觉得这非常有趣。

    XAML

      <ListView SelectionMode="Single" ItemsSource="{Binding Path=DisplayImages}" >
            <ListView.Resources>
               <Style TargetType="ListViewItem">
                   <Setter Property="ContextFlyout">
                        <Setter.Value>
                             <MenuFlyout>
                                <MenuFlyoutItem Text="Save Image" Icon="Save" Command="{Binding Path=SaveImageCommand}"/>
                             </MenuFlyout>
                        </Setter.Value>
                   </Setter>
                </Style>
      </ListView.Resources>
    

    C语言

    public ICommand SaveImageCommand { get; set; }
    SaveImageCommand = new CommandHandler(SaveImageExecuted, true);
    
    private async void SaveImageExecuted()
    {
    }
    

    我的命令处理程序

    public class CommandHandler : ICommand
    {
        private Action _action;
        private bool _canExecute;
        public CommandHandler(Action action, bool canExecute)
        {
            _action = action;
            _canExecute = canExecute;
        }
    
        public bool CanExecute(object parameter)
        {
            return _canExecute;
        }
    
        public event EventHandler CanExecuteChanged;
    
        public void Execute(object parameter)
        {
            _action();
        }
    }
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   DotNetRussell    7 年前

    所以我很确定这是框架中的一个bug。

    为了解决这个问题,我决定使用一个单击处理程序来调用viewModel中执行的命令。超级强基,但它起作用。

    XAML

        <MenuFlyoutItem Text="Save Image" Icon="Save" Click="OnSaveContextMenuClicked"/>
    

    隐藏代码

        private void OnSaveContextMenuClicked(object sender, RoutedEventArgs e)
        {
            viewModel.SaveImageCommand.Execute(sender);            
        }
    
        2
  •  1
  •   David Hollowell - MSFT    6 年前

    我也找到了另一个解决办法。 如果使用x:bind而不是binding设置menuflyoutitem命令属性,那么只要menuflyout具有x:name,这将有效。

    <MenuFlyout x:Name="MyMenuFlyout">
        <MenuFlyoutItem Text="Save Image" Icon="Save" Command="{x:Bind SaveImageCommand}"/>
    </MenuFlyout>