środa, 20 listopada 2013

MVVM Command

 CS file

public class ViewModel : INotifyPropertyChanged
{
    // INotifyPropertyChanged implementation

    // Properties implementation

    public ViewModel()
    {
        ActionCommand = new MyCommand();
        ActionCommand.CanExecuteFunc = obj => true;
        ActionCommand.ExecuteFunc = MyActionFunc;
     }

     public void MyActionFunc(object parameter)
     {
         //Operations
     }
}

public class MyCommand : ICommand
{
    public Predicate<object> CanExecuteFunc{ get; set; }
    public Action<object> ExecuteFunc { get; set; }

    public bool CanExecute(object parameter)
    {
        return CanExecuteFunc(parameter);
    }

    public event EventHandler CanExecuteChanged;
    public void Execute(object parameter)
    {
        ExecuteFunc(parameter);
    }
}

XAML file

 <Button Command="{Binding Path=ActionCommand}"
              CommandParameter="ParameterValue" />

XAML TwoWay Binding

CS file



public class ViewModel : INotifyPropertyChanged
{
  public event PropertyChangedEventHandler PropertyChanged;

  protected virtual void OnPropertyChanged(string propertyName)
  {
    var handler = PropertyChanged;
    if (handler != null)
    {
      handler(this, new PropertyChangedEventArgs(propertyName));
    }
  }

  private string _firstProperty;
  public string FirstProperty
  {
    get{ return _firstProperty; }
    set
    {
      if (_firstProperty == value)
        return
      else
        _firstProperty = value;
        OnPropertyChanged("FirstProperty");
        //propertyName in parentheses must be the same as property name
    }
  }
}

XAML file


<TextBox Text="{Binding Path=FirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>