1

I am pretty new to WPF and MVVM so this may be a very easy question. I have an app with a button and a checkbox. Once the button is clicked it runs a command that then runs a script. The checkbox is an option to view an internet browser as the script runs. I am wondering how I can pass in wheather the checkbox is checked or not once the button is selected. I changed some of the coding names to be more basic. Here is my Xaml:

<StackPanel Margin="10">
        <CheckBox Content="Option" IsChecked="True"  />
        <Button Height="20"
                Content="Run Script"
                Command="{Binding Script }"
                />
    </StackPanel>

And here is the the ViewModel:

class MainWindowViewModel
{
    public ICommand script{ get; set; }

    public MainWindowViewModel()
    {
        script = new RelayCommand(o => MainButtonClick());
    }

    private void MainButtonClick()
    {
        Program start = new Program();
        start.Begin();
    }
}
2
  • 2
    The easiest way is to use a CommandParameter. Commented Sep 25, 2019 at 10:25
  • @dymanoid Yes a CommandParameter could work, assuming the RelayCommand class can handle Parameters. So OP might need to adjust their RelayCommand, IMO binding the IsChecked property to the ViewModel is easier, and also allows for more parameters down the road Commented Sep 25, 2019 at 10:35

1 Answer 1

3

You can bind the IsChecked of the CheckBox to a property in the ViewModel. Something like this should work:

<CheckBox Content="Option" IsChecked="{Binding ShowBrowser}"  />
public bool ShowBrowser {get; set;}

You can then use the ShowBrowser property in your MainButtonClick method

Or you could use a Command Parameter as dymanoid pointed out in the comments. Like so:

<CheckBox Name="ShowBrowser" Content="Option" IsChecked="True"  />
<Button Height="20"
    Content="Run Script"
    Command="{Binding Script }"
    CommandParameter="{Binding ElementName=ShowBrowser, Path=IsChecked} 
    />

And then your Method would look like this:

private void MainButtonClick(bool showBrowser)
{
    Program start = new Program();
    start.Begin();
}

This is of course assuming your RelayCommand class can handle parameters

Sign up to request clarification or add additional context in comments.

1 Comment

That was incredibly simple... thank you so much! I will mark this as the answer once the ten minutes are up. Thank you again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.