Firedragon
Firedragon

Reputation: 3733

Triggering RelayCommand from code-behind

I have a Main Page for my application that is formed froma number of other windows. One of which is the settings for my applications and is open/closed by clicking a button from my Main Page. This window has a View Model as well as two buttons, Save and Cancel. Pressing Cancel is used to restore the previous settings and Save just stores them. Now, when I use the main menu to close the Properties I want the Cancel to be called and am wondering about the best way to do this.

So in my view model I have something like this:

public RelayCommand CancelRC { get; private set; }

public  PropertiesViewModel
{
    CancelRC = new RelayCommand(RestoreProperties)
}

private RestoreProperties
{
     // Restore
}

In my MainPage.xaml.cs

private void Properties_Click(object sender, RoutedEventArgs e)
{
    if (PropertiesForm.Visibility == Visibility.Collapsed)
    {
        PropertiesForm.Visibility = Visibility.Visible;
        PropertiesForm.IsSelected = true;
    }
    else
    {
        PropertiesForm.Visibility = Visibility.Collapsed;
        IncidentForm.IsSelected = true;

        // Send a Cancel relaycommand to the Properties View Model?
    }
}

The obvious solution to me is to trigger the RelayCommand manually but I am not sure this is the most appropriate way to do it and I am not sure how you would trigger that anyway. So it this the way to do it or is there a more preferred way to do something like this?

Similarly is manually hiding and showing the Properties via the Main Page like this the best way to do it?

Upvotes: 0

Views: 1516

Answers (1)

David
David

Reputation: 320

Remove the Properties_Click method and in your xaml do the following:

<Button Command="{Binding CancelRC}">Properties</Button>

This will cause the button to use RelayCommand.CanExecute and RelayCommand.Execute with no code on your part. The code assumes the window datacontext is set to your View Model.

Upvotes: 1

Related Questions