Home > Blockchain >  How to execute Button Command with Parameter without providing the Parameter when called in the View
How to execute Button Command with Parameter without providing the Parameter when called in the View

Time:10-21

I am new to MVVM pattern and I just wanted to ask what is the best way to "click" or execute a button command that has a command parameter of contentdialog from the ViewModel.

Example code: View

<Button Command="{x:Bind ViewModel.OpenContentDialog}" CommandParameter="{Binding ElementName=DialogBox}" Grid.Row="0" Grid.Column="3">Open Dialog</Button>

<ContentDialog x:Name="DialogBox"
           PrimaryButtonText="OK" IsPrimaryButtonEnabled="{Binding PrimaryButtonEnabled}"
           CloseButtonText="Cancel">
                                <ContentDialog.TitleTemplate>
                                    <DataTemplate>
                                        <StackPanel Orientation="Horizontal">
                                            <TextBlock Text="Dialog"/>
                                        </StackPanel>
                                    </DataTemplate>
                                </ContentDialog.TitleTemplate>
...

ViewModel

 public RelayCommand<object> OpenContentDialog => new RelayCommand<object>((dialog) => { SortDialog(dialog); });

I want to call the OpenContentDialog command in another ViewModel method like this:

OpenContentDialog.Execute(); //needs the parameter

I have tried passing the actual ContentDialog as a ViewModel Object, it works but I am not sure if that violates the MVVM pattern.

CodePudding user response:

If the command expects a ContentDialog to be passed as an argument, your two options are to either create such a ContentDialog programmatically before you call Execute or get a reference to an already existing dialog:

OpenContentDialog.Execute(
    new ContentDialog() { PrimaryButtonText = "OK", IsPrimaryButtonEnabled = true });
  • Related