0
votes

Suppose I'm using the MVVM approach (Silverlight)

I'm having all my buttons handled with commands.

Suppose I have a button used to navigate to a certain page, say we selected a customer in a grid and want to navigate to the customer's details view.

Can I handle this button with a DelegateCommand? How? Can I handle the navigation from the ViewModel? Am I forced to handle the navigation from the code-behind.

2
How do you navigate from page to page currently? Do you have a navigation service of some kind? If you would provide some code that would be very useful. - Faster Solutions
Now I'm using the code-behind approach: private void btnCustomer_Click(object sender, RoutedEventArgs e) { NavigationService.Navigate(new Uri("/CustomerDetails", UriKind.Relative)); } - Rafael
Open question: is navigation really a part of the ViewModel, or is it an implementation detail of the View? If the latter, you can stick to using code-behind, or HyperlinkButton, as needed. - jv42

2 Answers

0
votes

Here we go:

Xaml:

<Button Command="{Binding GoToCustomerDetailsPage}" Content="Customer Details"/>

ViewModel:

private INavigationService _navigationService;

public ViewModel(INavigationService navigationService)
{
    _navigationService=navigationService;
}
public ICommand GoToCustomerDetailsPage
{
    get{
        return new DelegateCommand(GoToCustDetailsPage,CanGoToCustDetailsPage);
        }
}

private void GoToCustDetailsPage()
{
    _navigationService.Navigate(new Uri("/CustomerDetails", UriKind.Relative));
}

private bool CanGoToCustDetailspage()
{
   return true;//Or some sensible code that determines if this is sensible.
}

Basically, the Command is bound to the button as per normal. The command is a property on the viewmodel. When the Command is executed it simply calls a private method in the viewmodel.

0
votes

here INavigationService not available.. It gives error if we add the namespace System.Windows.Navigation..