Search code examples
c#windows-runtimeappbarwinrt-component

How can I programatically tap an AppBarButton?


I have this code:

async private void InformUserOfRenameOption(string platypusName)
{
    CoreWindowDialog cwd = new CoreWindowDialog(String.Format(
        "This platypus has been given the default name {0}. Do you want to change it?", platypusName));
    cwd.Commands.Add(new UICommand { Label = "Yes", Id = 0 });
    cwd.Commands.Add(new UICommand { Label = "No", Id = 1 });
    cwd.Commands.Add(new UICommand { Label = "Cancel", Id = 2 });
    cwd.CancelCommandIndex = 2;
    IUICommand cmd = await cwd.ShowAsync();
    //if (cmd.Id == 0) <= 'Operator '==' cannot be applied to operands of type 'object' and 'int'
    if (Convert.ToInt32(cmd.Id) == 0)
    {
        appbarbtnRenamePlatypus.Tapped();
    }
} 

...but my attempt to programatically tap the AppBarButton fails with the compile-time error: "The event 'Windows.UI.Xaml.UIElement.Tapped' can only appear on the left hand side of += or -="

So how can I programatically tap the button or, more specifically, get its Button.Flyout Flyout to fly out?


Solution

  • Typically you would refactor the code from the AppBar button's click handler into its own method, then you can call it from anywhere.

    You could also consider using ICommand if you're feeling more adventurous -- this enables you to have any number of UI elements (eg ButtonBase.Command) or call it directly from code.