/// <summary> /// Creates system-style buttons if requested and hooks up CanExecuteChanged for the ToolbarItem command. /// (after writing this I noticed that the latter will be in the next version of Forms... oh well) /// </summary> /// <param name="toolbarItem"></param> /// <returns></returns> private UIBarButtonItem CreateUIBarButtonItem(ToolbarItemEx toolbarItem) { UIBarButtonSystemItem? systemItem = null; switch (toolbarItem.ToolbarItemType) { case ToolbarItemType.Done: systemItem = UIBarButtonSystemItem.Done; break; case ToolbarItemType.Add: systemItem = UIBarButtonSystemItem.Add; break; } var buttonItem = systemItem != null ? new UIBarButtonItem(systemItem.Value, (s, e) => toolbarItem.Activate()) : toolbarItem.ToUIBarButtonItem(); // Xamarin.Forms 1.3.2 adds support for CanExecute, so we only need this for // our custom system buttons // if (systemItem != null) { var command = toolbarItem.Command; EventHandler canExecuteHandler = (s, e) => UpdateButtonState(toolbarItem, buttonItem); command.CanExecuteChanged += canExecuteHandler; toolbarItem.PropertyChanged += (s, e) => { if (e.PropertyName == ToolbarItem.CommandProperty.PropertyName) { command.CanExecuteChanged -= canExecuteHandler; UpdateButtonState(toolbarItem, buttonItem); toolbarItem.Command.CanExecuteChanged += canExecuteHandler; } }; UpdateButtonState(toolbarItem, buttonItem); } return buttonItem; }
private static void UpdateButtonState(ToolbarItemEx toolbarItem, UIBarButtonItem buttonItem) { buttonItem.Enabled = toolbarItem.Command.CanExecute(toolbarItem.CommandParameter); }