开发者

Calling "function" on control

开发者 https://www.devze.com 2022-12-25 20:53 出处:网络
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

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 fro开发者_如何学编程ntend)?

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号