DotNetRussell
DotNetRussell

Reputation: 9857

Command Binding not working within Flyout or FlyoutMenu

So my other buttons that are all rigged in a identical way, within the same view and viewmodel, work fine.

This one however, which happens to be inside a context menu, doesn't. There aren't any binding expression errors either even when I change the command binding to something I know doesn't exist, which I find super interesting

The 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>

The C#

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

private async void SaveImageExecuted()
{
}

My command handler

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();
    }
}

Upvotes: 4

Views: 996

Answers (2)

David Hollowell - MSFT
David Hollowell - MSFT

Reputation: 1065

I've found another workaround for this too. If you set the MenuFlyoutItem Command property using x:Bind instead of Binding, this will work, so long as the MenuFlyout has an x:Name.

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

Upvotes: 1

DotNetRussell
DotNetRussell

Reputation: 9857

So I'm PRETTY sure this is a bug in the framework.

To work around it I decided to just use a click handler to invoke the executed command in the viewmodel. Super janky but it works.

XAML

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

Behind Code

    private void OnSaveContextMenuClicked(object sender, RoutedEventArgs e)
    {
        viewModel.SaveImageCommand.Execute(sender);            
    }

Upvotes: 1

Related Questions