I have a WPF application in which i'd like to change its design pattern to MVVM
.I have used this snippet
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FirstMVVm.Model;
using System.ComponentModel;
using System.Windows.Input;
using System.Windows;
namespace FirstMVVm.ModelView
{
class MyViewModel: INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private float result;
public float Result
{
get { return result; }
private set
{
if (result != value) {
result = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Result"));
}
}
}
}
public int Number { get; set; }
private RelayCommand _calculatePerimeterCommand;
public ICommand CalculatePerimeterCommand
{
get
{
if (_calculatePerimeterCommand == null)
{
_calculatePerimeterCommand = new RelayCommand(param => this.CalculatePerimeter());
}
return _calculatePerimeterCommand;
}
}
private MyModel _model;
public MyViewModel() {
_model = new MyModel();
}
private void CalculatePerimeter(){
Result = _model.Perimetre(Number);
}
}
}
The problem is that the RelayCommand
type is not known and i don't know what is the assembly missing.
Thanks,
RelayCommand is a class created by MS for handling event or command in WPF. you can create own class or go through below link.
http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
This does not necessarily have to be RelayCommand
it's simply a name of class from most common example on the web.
The mechanism of ICommand
works in a way that instead of getter or setter being called you get public void Execute(object parameter)
to be called on class that is implementing ICommand
Let me give you an example:
I have a hyperlink which when clicked should do some stuff before redirecting person to browser.
XAML
<Hyperlink NavigateUri="https://payments.epdq.co.uk/ncol/prod/backoffice/"
Command="{Binding Path=NavigateToTakePayment}" IsEnabled="{Binding CanTakePayment}">
Launch Payments Portal
</Hyperlink>
now in viewModel I have property
public ICommand NavigateToTakePayment
{
get { return _navigateToTakePayment ?? (_navigateToTakePayment = new NavigateToTakePaymentCommand(this)); }
set { _navigateToTakePayment = value; }
}
but when hyperlink is clicked instead of getter being fired like one would expect NavigateToTakePaymentCommand
class Execute
method is fired instead.
public class NavigateToTakePaymentCommand : ICommand
{
public NavigateToTakePaymentCommand(PaymentViewModel paymentViewModel)
{
ViewModel = paymentViewModel;
}
public PaymentViewModel ViewModel { get; set; }
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
//your implementation stuff goes here.
}
public event EventHandler CanExecuteChanged;
}
I hope this example will clarify how the mechanism works and will save you some time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With