Universal / secure implementation of ICommand?

I recently started using WPF and MVVM, one thing I would like to do is to have a secure implementation like ICommand , so I don’t have to enter all the parameters of the command.

Does anyone know how to do this?

+8
generics c # wpf mvvm
source share
2 answers

Do not use this syntax, as you probably found:

error CS0701: `` System.Func`` is not a valid limitation. The constraint must be an interface, non-printable class, or type parameter

It is best to enclose the semantics of Func<E,bool> in an interface, for example:

 interface IFunctor<E> { bool Execute(E value); } 

and then use this interface in the class definition. Although, I am interested in what you want to accomplish, as there may be a different approach to your problem.

In a comment, that @Alex is looking for a strongly typed implementation of ICommand :

 public FuncCommand<TParameter> : Command { private Predicate<TParameter> canExecute; private Action<TParameter> execute; public FuncCommand(Predicate<TParameter> canExecute, Action<TParameter> execute) { this.canExecute = canExecute; this.execute = execute; } public override bool CanExecute(object parameter) { if (this.canExecute == null) return true; return this.canExecute((TParameter)parameter); } public override void Execute(object parameter) { this.execute((TParameter)parameter); } } 

Used like this:

 public class OtherViewModel : ViewModelBase { public string Name { get; set; } public OtherViewModel(string name) { this.Name = name; } } public class MyViewModel : ViewModelBase { public ObservableCollection<OtherViewModel> Items { get; private set; } public ICommand AddCommand { get; private set; } public ICommand RemoveCommand { get; private set; } public MyViewModel() { this.Items = new ObservableCollection<OtherViewModel>(); this.AddCommand = new FuncCommand<string>( (name) => !String.IsNullOrEmpty(name), (name) => this.Items.Add(new OtherViewModel(name))); this.RemoveCommand = new FuncCommand<OtherViewModel>( (vm) => vm != null, (vm) => this.Items.Remove(vm)); } } 

XAML:

 <ListBox x:Name="Items" ItemsSource="{Binding Items}" /> <Button Content="Remove" Command="{Binding RemoveCommand}" CommandParameter="{Binding SelectedItem, ElementName=Items}" /> <StackPanel Orientation="Horizontal"> <TextBox x:Name="NewName" /> <Button Content="Add" Command="{Binding AddCommand}" CommandParameter="{Binding Text, ElementName=NewName}" /> </StackPanel> 

I would recommend using Microsoft DelegateCommand or RelayCommand , or any other implementation of any of them.

+10
source share

Your command class should subscribe to ICommand and define CanExecuteChanged, as shown below.

 public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } 
0
source share

All Articles