質問

I need to get some code which uses both CommandPattern and WPF.. Say.. I am using the MVVM pattern coding. And I need to use some cammand patterns.

Like "MenuItem Header="New" HorizontalAlignment="Left" Width="130" Command="{Binding Add}""

and my command is implemented using CommandPattern

役に立ちましたか?

解決

An implementation of the Command Pattern would look like this...

        <Menu DockPanel.Dock="Top">
            <MenuItem Header="file" Command="{Binding FileCommand}"/>
        </Menu>

...which declares an item bound to a command. The command would exist in the View Model with a declaration like this...

    public ICommand FileCommand { get; set; }

... where ICommand is declared as an interface in the System.Windows.Input name space. http://msdn.microsoft.com/en-us/library/system.windows.input.icommand.aspx

To initialize the ICommand...

FileCommand = new RelayCommand(FileCommandExecute, FileCommandCanExecute); 

...where 'RelayCommand' is a class explained in Josh Smith's seminal article on MVVM which is found here: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx Other implementations exist, like Prism's 'DelegateCommand'. The two delegates in the constructor are coded like this...

    #region FileCommand callbacks
    private bool FileCommandCanExecute(object obj)
    {
        return true;
    }
    private void FileCommandExecute(object obj)
    {
        OpenFile();
    }
    #endregion // end of FileCommand callbacks

...where the 'CanExecute' method enables or disables the command on the user surface depending upon the View Model's state. And the 'Execute' method performs the actual work.

This example is a classical MVVM implementation of the command pattern. In your parlance, the View Model implementing the command is the 'receiver' and the View containing the menu is the 'invoker'. More recent implementations of the command pattern have been introduced such as the 'CompositeCommand' and 'Attached Behaviour', but these are outside the scope of your question.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top