tags:

views:

47

answers:

1

Hi,

I'm using MVVM in my WPF project. Now I want to display a subwindow when someone presses a button. To achieve this classically I would call the Show() method. What I want now, to keep my application clear, is to bind the button to the Show() function of the subwindow.

As the button click (menu click, whatever) is not always allowed I wrote a custom command that evaluates if the command can be executed. However, I did not found a clue how to call the function of that control in a clean way. Is this the point to do some classic style (code in the frontend)?

Edit (to include code)

XAML:

        <MenuItem Foreground="White" Header="File">
            <MenuItem Header="Login" Background="#FF444444" Command="{Binding Dialog.ApplicationLoginCommand}" />
            <MenuItem Header="Logout" Background="#FF444444" Command="{Binding Dialog.ApplicationLogoutCommand}" />
            <MenuItem Header="Exit" Background="#FF444444" Command="{Binding Dialog.ApplicationShutdownCommand}" />
        </MenuItem>

C#:

public class ApplicationDisplayLoginCommand : ICustomCommand {
    private MyViewModel _ViewModel = null;

    public ApplicationDisplayLoginCommand( MoneyManagementViewModel vm ) {
      _ViewModel = vm;
    }

    #region ICustomCommand Members

    public event CustomCommandExecutedDelegate CustomCommandExecuted;

    #endregion

    #region ICommand Members

    public bool CanExecute( object parameter ) {
      return ! _ViewModel.IsLoggedIn;
    }

    public event EventHandler CanExecuteChanged {
      add {
        CommandManager.RequerySuggested += value;
      }
      remove {
        CommandManager.RequerySuggested -= value;
      }
    }

    public void Execute( object parameter ) {
      if (null != CustomCommandExecuted) {
        CustomCommandExecuted ();
      }
          _ViewModel.Login ();
    }
}

ICustomCommand inherits from ICommand, just to add event, since one Command is specific to different frontends, that require the command to behave differently.

HTH

-sa

+1  A: 

You can't bind to a method, only to a property. If you need to open a new window from your ViewModel, have a look at this article by Josh Smith. It shows how to display a message box by using a Service Locator. You can easily adapt the code to display any window

Thomas Levesque
Would function and a nice article linked to.
Sascha