Friday, January 7, 2011

Silverlight, PRISM, MVVM, MEF – Part 2

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}" />
Namespace implementations
You can also pass command parameters using the CommandParameter property.
In the view model the SearchCommand implementation is defined as
public class EmployeeViewModel : NotificationObject
    public EmployeeViewModel(IEmployeeRepository employeeRepository)
        _employeeRepository = employeeRepository;
        PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler((x, y) => RaiseCommandChangedEvent());

    private void RaiseCommandChangedEvent()

    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…


1 comment:

wenyonk said...

Another great Blog, thank you for sharing this information!