Looking for a good way to check which button was pressed with the command pattern.

Markus Freitag 3,786 Reputation points
2020-07-31T06:57:23.35+00:00

Hello,

I'm looking for a good way to check which button was pressed with the command pattern.
Maybe you can make s sample with more buttons

  • OK
  • Cancel
  • Yes
  • No
  • Wait public partial class MessageBoxTest : Window
    {
    public MessageBoxTest()
    {
    InitializeComponent();
    this.DataContext = this;
    }
    public static object ShowDialog(string msg) => (new MessageBoxTest() { Message = msg }).ShowDialog();
        public string Message { get; set; }
    
        public ICommand Cmd { get => new RelayCommand((state) => { ExitMessageBox((state != null && state.ToString() == "True")); }); }
    
        private void ExitMessageBox(bool result)
        {
            this.DialogResult = result;
            this.Close();
        }
    }
    
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,691 questions
0 comments No comments
{count} votes

Accepted answer
  1. Peter Fleischer (former MVP) 19,306 Reputation points
    2020-07-31T15:02:26.603+00:00

    Hi Markus,
    you can use CommandParameter and use this value as return from ShowDialog, like this:

        <Button Content="No" HorizontalAlignment="left" Margin="5" Width="100"   
                Command="{Binding}" CommandParameter="No"/>  
        <Button Content="Yes" HorizontalAlignment="Right" Margin="5" Width="100"    
                Command="{Binding}" CommandParameter="Yes"/>  
    

    And CodeBehind:

    14971-x.png

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Andy ONeill 361 Reputation points
    2020-07-31T19:25:53.997+00:00

    Usually, with commands I would bind a relaycommand or delegatecommand specific to each button rather than having some generic way to handle all buttons.

    Where you want generic handling this is usually you want exactly the same process but with different parameters.
    This is often more view orientated, in my experience.
    A concrete example being a custom keyboard control I built.
    This used one click handler for numerous buttons and the character to send was in the Tag of each button.

    There are exceptions.

    The very basic sample here passes a Type in via command parameter:

    52485.wpf-tips-and-tricks-using-contentcontrol-instead-of-frame-and-page-for-navigation.aspx

    For a mvvm friendly way to handle commands in a dialog I usually provide commands from a viewmodel to a control in the view that handles showing the dialog.

    31416.wpf-mvvm-friendly-user-notification.aspx

    1 person found this answer helpful.