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.
user7116
source share