Friday, January 07th, 2011

Actions or operations that can be performed in the view model are implemented as commands.  Commands provide a convenient way to represent actions or operations that can be easily bound to controls in the UI. They encapsulate the actual code that implements the action or operation and help to keep it decoupled from its actual visual representation in the view.

Commands are implemented in the ViewModel either as CommandMethods or ICommand implementations.  The ICommand objects defines an Execute and CanExecute method which encapsulate the action logic. Prism has a DelegateCommand implementation which implements the ICommand interface. The DelegateCommand’s constructor allows you to define the delegates for the Execute and CanExecute actions.  For e.g the XAML given below shows a button that is bound to a DelegateCommand.

<StackPanel Orientation=”Horizontal” Grid.Row=”1″ HorizontalAlignment=”Right” Margin=”0 15 0 0″>

<TextBlock Text=”Search text: ” VerticalAlignment=”Center” />

<TextBox Width=”240″ Text=”{Binding SearchText, Mode=TwoWay}” />

<Button Content=”Search” prism:Click.Command=”{Binding SearchCommand}” />

</StackPanel>

Namespace implementations

xmlns:prism=”http://www.codeplex.com/prism”

You can also pass command parameters using the CommandParameter property.

In the view model the SearchCommand implementation is defined as

[Export]

[PartCreationPolicy(CreationPolicy.NonShared)]

public class EmployeeViewModel : NotificationObject

{

[ImportingConstructor]

public EmployeeViewModel(IEmployeeRepository employeeRepository)

{

_employeeRepository = employeeRepository;

GetEmployees();

SetCommands();

PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler((x, y) => RaiseCommandChangedEvent());

}

private void RaiseCommandChangedEvent()

{

SearchCommand.RaiseCanExecuteChanged();

}

private void SetCommands()

{

SearchCommand = new DelegateCommand(() => FilterEmployees(), () => !string.IsNullOrEmpty(SearchText));

}

public DelegateCommand SearchCommand { get; private set; }

private void FilterEmployees()

{

//Filter employees here…

}

//Rest of the code…

}

Category: .Net, Silverlight | Tags: , ,
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

One Response

  1. 1
    Corey 

    Great post, really enjoyed it!
    — Corey

    http://www.bigconceptdesigns.com

Leave a Reply


 

Spam Protection by WP-SpamFree Plugin