RaiseCanExecuteChanged更方便

时间:2013-05-14 02:49:05

标签: command

当CanExecute条件发生变化时,我想要RaiseCanExecuteChanged。 E.g:

public class ViewModel
{
public viewModel()
{
    Command = new RelayCommand(action,condition);
}

private  bool condition()
{
   return  this.Condition1&&this.Condition2&&this.Condition3;
}

public bool Condition1
{
  get{...}
  set{.... **command.RaiseCanExecuteChanged();}**
}
public bool Condition2
{
   get{...}
   set{.... command.**RaiseCanExecuteChanged();}**
}
public bool Condition3
{
  get{...}
  set{.... **command.RaiseCanExecuteChanged();}**
}

}

工作正常。 但我不喜欢写这么多RaiseCanExecuteChanged,我想自动设置这些更改。 例如    在RelayCommand中,创建一个名为RaiseChanged

的新方法
  public void RaiseChanged(XXXXXX  XXX,  params string[] propertyNames)
  {
      // for each property in propertyNames,
     // RaiseCanExecuteChanged();
  }

我将ViewModel vm作为参数,并使用vm.PropertyChanged + =(s,e)=> {}   但我认为这不是一个很好的方法。

有没有人有其他想法?

1 个答案:

答案 0 :(得分:0)

我开发了我的解决方案,我可以这样做:

C#View Model:

public bool CanExecuteMethod(object sender)
      {
      }
public void ButtonExecuteMethod(object sender)
      {
      }

public event Action EventNotifyCanExecuteChanged;

private Action _DelegateNotifyCanExecuteChanged;
public Action DelegateNotifyCanExecuteChanged
     {
         get { return _DelegateNotifyCanExecuteChanged; }
         set { _DelegateNotifyCanExecuteChanged = value; }
     }

public void CanExecuteFlag
        {
   if (EventNotifyCanExecuteChanged != null) { EventNotifyCanExecuteChanged(); }
   if (_DelegateNotifyCanExecuteChanged != null) { _DelegateNotifyCanExecuteChanged();} 
        }

XAML:

< Button Content="Button Cmd-ExCeCh" HorizontalAlignment="Left" Margin="27,231,0,0"
         VerticalAlignment="Top" Width="120"
        Command="{mark:BindCommandResource MainWindowViewModel,
        ExecuteMethodName=ButtonExecuteMethod,
        CanExecuteMethodName=CanExecuteMethod,
        EventToInvokeCanExecuteChanged=EventNotifyCanExecuteChanged,
        PropertyActionCanExecuteChanged=DelegateNotifyCanExecuteChanged}"  />

我在我的开源项目MVVM-WPF XAML标记绑定扩展中放置/共享此解决方案 - http://wpfmvvmbindingext.codeplex.com