Search code examples
wpfribbon

WPF RibbonButton


How can I programatically set the text on a RibbonButton? Right now I have the code below, but the button does not display 'Browse'. Any suggestions?

RibbonButton btn = new RibbonButton();
btn.Name = "btnBrowse";
btn.Content = "Browse";
btn.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
btn.Click += new RoutedEventHandler(btn_Click);

Solution

  • RibbonButtons from the RibbonControlsLibrary behave differently than standard WPF buttons and need a command to display text. The command is where you also assign the images and other items such as tool tips.

    var cmd = new RibbonCommand();
    cmd.LabelTitle = "Browse";
    cmd.CanExecute += ( sender, args ) => args.CanExecute = true;
    cmd.Executed +=new ExecutedRoutedEventHandler(cmd_Executed);
    
    var btn = new RibbonButton();
    btn.Command = cmd;
    
    MyRibbonGroup.Controls.Add( btn );
    

    You must assign true to CanExecute, otherwise will the command/button will always be disabled. The CanExecute method can have your business logic disable or enable the command/button as well.