Make Command's CanExecute depend on other field's value - c#

I'm working on a small WPF MVVM application. In essence, the user browses for a file, then clicks "Execute" to run some code on the file.
In my view model class, I've bound the two button clicks ("Browse" and "Execute") to an ICommand.
internal class DelegateCommand : ICommand
{
private readonly Action _action;
public DelegateCommand(Action action)
{
_action = action;
}
public void Execute(object parameter)
{
_action();
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
}
internal class Presenter : INotifyPropertyChanged // VM class
{
private string filePath;
public string FilePath
{
get { return filePath; }
set
{
filePath = value;
RaisePropertyChangedEvent("FilePath");
}
}
public ICommand ExecuteCommand
{
// returns a DelegateCommand
}
public ICommand BrowseCommand
{
// how to enable/disable button based on whether or not a file has been selected?
}
}
Here, CanExecute always returns true. What I'd like to have happen, though, is for CanExecute to be tied to whether or not a file has been selected (i.e. to whether or not FilePath.Length > 0) and then link the button's status (enabled/disabled) to that. What's the best way to do this without adding an IsFileSelected observable property to Presenter?

Usually i have a base class for ICommand instances that takes a delegate for both its Execute and CanExecute methods. That being the case you can capture things in scope via closures. e.g. something along those lines:
private readonly DelegateCommand _executeCommand;
public DelegateCommand ExecuteCommand { /* get only */ }
public Presenter()
{
_excuteCommand = new DelegateCommand
(
() => /* execute code here */,
() => FilePath != null /* this is can-execute */
);
}
public string FilePath
{
get { return filePath; }
set
{
filePath = value;
RaisePropertyChangedEvent("FilePath");
ExecuteCommand.OnCanExecuteChanged(); // So the bound control updates
}
}

Related

Can I extend the command class so that the button that binds to it is automatically disabled?

In my application I bound my buttons to commands with "MVVM".
My command is implemented as follows:
public Command CommandLoadStuff
{
get
{
return new Command(async () =>
{
await DoLongStuff();
});
}
}
The problem is that these commands are async and the user can click them multiple times causing the code to execute multiple times also.
As a first approach i used CanExecute:
public Command CommandLoadStuff
{
get
{
return new Command(async () =>
{
AppIsBusy = true;
await DoLongStuff();
AppIsBusy = false;
},() => !AppIsBusy);
}
}
Now I wonder if there isn't a better way than to handle the CanExecute for each command individually.
Since I initialize the command every time with "new" I wonder if the class "Command" could not be extended accordingly. It should block a second click of the button during the lifespan with CanExecute (Posibly in the Constructor?) and release it after the execution of the command is finished. ( Possibly in the Dispose function?)
Is there a way to achieve this?
Extending the class command this way is not possible, as far as I can tell, because Execute is non-virtual and you have to pass the execute action to the constructor. Anyway, there is still a way. Command derives from ICommand which has the following interface
public interface ICommand
{
event EventHandler CanExecuteChanged;
void Execute(object data);
bool CanExecute(object data);
}
You could create a class AsyncBlockingCommand (or whatsoever) that will return will return the respective value from CanExecute depending on whether an async method is still running (I know that there are issues with async void methods, so handle with care)
public class AsyncBlockingCommand : ICommand
{
bool _canExecute = true;
Func<Task> _toExecute;
public AsyncBlockingCommand(Func<Task> toExecute)
{
_toExecute = toExecute;
}
public event EventHandler CanExecuteChanged;
public async void Execute(object data)
{
_canExecute = false;
RaiseCanExecuteChanged();
await _toExecute();
_canExecute = true;
RaiseCanExecuteChanged();
}
public bool CanExecute(object data) => _canExecute;
private void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
}
Before your async method is executed, _canExecute is set to false and CanExecuteChanged is raised. This way, your Button will get notified of CanExecute having changed and disable itself. Vice versa after the async method has been called. (Probably the RaiseCanExecuteChanged will have to be invoked on the main thread.)
You can use IsEnabled property to make the Button cannot be clicked.
Like following code.
<Button
Text="click"
Command={Binding Button1Command}
IsEnabled={Binding AreButtonsEnabled} />
If the value of IsEnabled is false, you can see this button, it is grey, if you click it, it will not execute any command.
Here is MyViewModel code.
private bool _areButtonsEnabled = true;
public bool AreButtonsEnabled
{
get => _areButtonsEnabled;
set
{
if (_areButtonsEnabled != value)
{
_areButtonsEnabled = value;
OnPropertyChanged(nameof(AreButtonsEnabled)); // assuming your view model implements INotifyPropertyChanged
}
}
}
public ICommand Button1Command { get; protected set; }
public MyViewModel()
{
Button1Command = new Command(HandleButton1Tapped);
}
private void HandleButton1Tapped()
{
// Run on the main thread, to make sure that it is getting/setting the proper value for AreButtonsEnabled
// And note that calls to Device.BeginInvokeOnMainThread are queued, therefore
// you can be assured that AreButtonsEnabled will be set to false by one button's command
// before the value of AreButtonsEnabled is checked by another button's command.
// (Assuming you don't change the value of AreButtonsEnabled on another thread)
Device.BeginInvokeOnMainThread(async() =>
{
if (AreButtonsEnabled)
{
AreButtonsEnabled = false;
// DoLongStuff code
await Task.Delay(2000);
AreButtonsEnabled = true;
}
});
}

redundant ICommand class for wpf mvvm

I'm still learning about wpf, however I'm familiar withe how to setup mvvm in wpf c#. However when it comes to the ICommand/RelayCommand stuff, its a bit of a confusing area for me. Over the past few months I've compiled a few implementations of the ICommand classes in order to create my tools. However I'm at the point now where I've read a few articles and I've looked at the code long enough, I'm looking for someone to help me out and put into simple terms what is going on here and if so, how can I combine/clean up these classes. At the moment the code seems redundant and I'm not sure how to go about optimizing it. Hope this isn't asking for to much. Thanks.
The two important things I want to maintain in this, is the ability to pass arguments to the commands as seen in this first usage example of RelayCommand. Secondly the ability to enable/disable a command as seen in the second command.
So in my tool i have this helper class.
1. I don't get the differences of use between the two classes inside this RelayCommand.cs. There is a public and an internal class.
2. Is there a need for both or can they be combine?
RelayCommand.cs
using System;
using System.Windows.Input;
namespace WpfApplication1.Helper
{
public class RelayCommand<T> : ICommand
{
private readonly Action<T> execute;
private readonly Predicate<T> canExecute;
public RelayCommand(Action<T> execute, Predicate<T> canExecute = null)
{
if (execute == null)
throw new ArgumentNullException("execute");
this.execute = execute;
this.canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
if (parameter == null)
{
return true;
}
else
{
return canExecute == null || canExecute((T)parameter);
}
}
public void Execute(object parameter)
{
execute((T)parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
}
// added
internal class RelayCommand : ICommand
{
private readonly Predicate<object> canExecute;
private readonly Action<object> execute;
public RelayCommand(Action<object> execute, Predicate<object> canExecute = null)
{
if (execute == null)
throw new ArgumentNullException("execute");
this.execute = execute;
this.canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return canExecute == null || canExecute(parameter);
}
public void Execute(object parameter)
{
execute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
}
}
An example of me using the RelayCommand.cs in my class object called Customer.cs
private ICommand addNewLicense_Command;
public ICommand AddNewLicense_Command
{
get
{
return addNewLicense_Command ?? (addNewLicense_Command = new RelayCommand<Customer>(n =>
{
AddNewLicense_Execute(n);
}));
}
}
So then in my MainViewModel.cs i have another ICommand Class in the same project my Helper class mentioned above is part of. Is this class necessary? It seems so similar to the RelayCommand class.
public class CommandHandler : ICommand
{
private Action _action;
private bool _canExecute;
public CommandHandler(Action action, bool canExecute)
{
_action = action;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_action();
}
}
An example of me using CommandHandler in my MainViewModel.cs
private ICommand addNewUser_Command;
public ICommand AddNewUser_Command
{
get
{
return addNewUser_Command ?? (addNewUser_Command = new CommandHandler(() => AddNewUser_Execute(), true));
}
}
If you use a library like MVVM Lite then it will provide the RelayCommand implementations for you. Either way use the non-generic when you don't need a parameter passed in e.g. an "Ok" button:
public ICommand OkCommand { get { return new RelayCommand(Ok); } }
protected virtual void Ok()
{
// ... do something ...
}
The associated XAML is something like:
<Button Content="Ok" Command="{Binding OkCommand}" IsDefault="True" />
Use the generic when you want to pass a parameter:
public ICommand OpenClientCommand { get { return new RelayCommand<Client>(OnOpenClient); } }
private void OnOpenClient(Client client)
{
// ... do something with client ...
}
In this case you need to pass in a Client object via the command parameter:
<Button Content="Open" Command="{Binding OpenClientCommand}" CommandParameter="{Binding SelectedClient}"/>
Passing parameters is also handy when used with event triggers, e.g. you can add something like this to intercept your MainWindow's Closing event:
<i:Interaction.Triggers>
<i:EventTrigger EventName="Closing">
<cmd:EventToCommand Command="{Binding ClosingCommand}" PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
This trigger passes the message arguments into your handler which gives you the opportunity to cancel it in the event that the user hasn't saved their changes:
public ICommand ClosingCommand { get { return new RelayCommand<CancelEventArgs>(OnClosing); } }
private void OnClosing(CancelEventArgs args)
{
if (!PromptUserForClose())
args.Cancel = true;
}
The RelayCommand you have is all you need. If you want to disable the command you can pass a method in the constructor do do so:
return addNewLicense_Command ?? (addNewLicense_Command = new RelayCommand<Customer>(n =>
{
AddNewLicense_Execute(n);
},AllowAddNeLicense));
...
bool AllowAddNewLicense()
{
return _allowAddEnabled;
}
The second class called CommandHandler is just another implementation of ICommand. The difference is that you can pass the "enabled" boolean inside the constructor, which means it will remain the same unless you create a new instance of it. While in the RelayCommand you can pass a function that gets executed everytime* so you can influence the outcome.

How to implement ICommand without parameters

In my project, i'd like to use MVVM (& Commands). I've started learning about commands and implementation of ICommand.
I'd like to create implementation of ICommand without parameters.
(To trigger loading of data/flushing of data etc. - I don't need any parameters to do it, so it just seems natural to try and create command without parameters)
This is the code I'm using:
using System.Windows.Input;
public class NoParameterCommand : ICommand
{
private Action executeDelegate = null;
private Func<bool> canExecuteDelegate = null;
public event EventHandler CanExecuteChanged = null;
public NoParameterCommand(Action execute)
{
executeDelegate = execute;
canExecuteDelegate = () => { return true; };
}
public NoParameterCommand(Action execute, Func<bool> canExecute)
{
executeDelegate = execute;
canExecuteDelegate = canExecute;
}
public bool CanExecute()
{
return canExecuteDelegate();
}
public void Execute()
{
if (executeDelegate != null)
{
executeDelegate();
}
}
}
But i got errors about not implementing the ICommand interface in the right manner
('XXX.YYYY.NoParameterCommand' does not implement interface member 'System.Windows.Input.ICommand.Execute(object)')
So I thought about doing it like this instead:
(Added the parameters that were missing from CanExecute and Execute)
public class NoParameterCommand : ICommand
{
...omitted - no changes here...
public bool CanExecute(object parameter) //here I added parameter
{
return canExecuteDelegate();
}
public void Execute(object parameter) //and here
{
if (executeDelegate != null)
{
executeDelegate();
}
}
}
IS THIS A GOOD WAY TO DO IT?
SHOULD I USE ANOTHER WAY? (IF SO, WHAT SHOULD I DO INSTEAD?)
This is a good way to do it.
No, you should not use another way.
Additional suggestions:
Thinking about this again, I would improve your architecture by introducing an additional hierarchy level where CanExecute() and Execute() are abstract. From that class, derive your command class that invokes delegates.
This way, you can decide later on whether you want to supply your logic for your parameterless commands via delegates or via subclassing your base command class.
I'm not really sure what your concern is. It is common to ignore the parameters in the ICommand interface.
If you really want CanExecute and Execute methods that don't have parameters, you can implement the interface explicitly (rather than implicitly). The ICommand methods will still exist, but to anyone looking at your object from the outside, they won't be able to see those methods:
bool ICommand.CanExecute(object parameter) { this.CanExecute(); }
public bool CanExecute()
{
//do work
}
You are essentially hiding the interface implemenation. If someone wants to directly call the CanExecute method from the interface, they would have to type cast to ICommand in order to do it. You really don't gain anything in doing it this way, but if you are concerned with how your class looks to outside developers (e.g. you are developing an API), then this can make it look a little cleaner as you are letting them know you do not require any parameters.
I personally prefer it this way:
public class MyCommand : ICommand
{
private static bool True() { return true; }
private readonly Action _execute;
private Func<bool> _canExecute;
private Func<bool> _isVisible;
public event EventHandler IsVisibleChanged;
public event EventHandler CanExecuteChanged;
public MyCommand(Action execute, Func<bool> canExecute = null, Func<bool> isVisible = null)
{
_execute = execute;
_canExecute = canExecute ?? True;
_isVisible = isVisible ?? True;
}
public void Execute()
{
_execute();
}
public Func<bool> CanExecute
{
set
{
_canExecute = value ?? True;
CanExecuteChanged(this, new EventArgs());
}
get { return _canExecute; }
}
public Func<bool> IsVisible
{
set
{
_isVisible = value ?? True;
IsVisibleChanged(this, new EventArgs());
}
get { return _isVisible; }
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute();
}
void ICommand.Execute(object parameter)
{
Execute();
}
}
However, since the delegates usually don't change, I prefer an immutable version:
[ImmutableObject(true)]
public class MyImmutableCommand : ICommand
{
private static bool True() { return true; }
private readonly Action _execute;
private readonly Func<bool> _canExecute;
private readonly Func<bool> _isVisible;
[Obsolete("Will not be invoked, because the implementation never changes.")]
public event EventHandler CanExecuteChanged;
public MyImmutableCommand(Action execute, Func<bool> canExecute = null, Func<bool> isVisible = null)
{
_execute = execute;
_canExecute = canExecute ?? True;
_isVisible = isVisible ?? True;
}
public bool CanExecute()
{
return _canExecute();
}
public bool IsVisible()
{
return _isVisible();
}
public void Execute()
{
_execute();
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute();
}
void ICommand.Execute(object parameter)
{
Execute();
}
}

Correctly Using CanExecute for MVVM Light ICommand

I am starting to learn MVVM in C# and I was wondering how to correctly use the CanExecute method for an ICommand in MVVM Light. My WPF application is in VS 2012 C# 4.5 framework.
How to correctly implement CanExecute?
I have just been returning true, but I know there is a proper way to handle it. Maybe
if(parameter != null)
{
return true;
}
Here is some of the sample code.
private RelayCommand sendCommand;
public ICommand SendCommand
{
get
{
if (sendCommand == null)
sendCommand = new RelayCommand(p => SendStuffMethod(p), p => CanSendStuff(p));
return sendCommand;
}
}
private bool CanSendStuff(object parameter)
{
return true;
}
private void SendStuffMethod(object parameter)
{
string[] samples = (string[])parameter;
foreach(var sample in samples)
{
//Execute Stuff
}
}
Declare command
public ICommand SaveCommand { get; set; }
In constructor:
public SelectedOrderViewModel()
{
SaveCommand = new RelayCommand(ExecuteSaveCommand, CanExecuteSaveCommand);
}
Methods:
private bool CanExecuteSaveCommand()
{
return SelectedOrder.ContactName != null;
}
private void ExecuteSaveCommand()
{
Save();
}
http://www.identitymine.com/forward/2009/09/using-relaycommands-in-silverlight-and-wpf/
http://matthamilton.net/commandbindings-with-mvvm
http://www.c-sharpcorner.com/UploadFile/1a81c5/a-simple-wpf-application-implementing-mvvm/
bool CanSendStuff(object parameter);
//
// Summary:
// Defines the method to be called when the command is invoked.
//
// Parameters:
// parameter:
// Data used by the command. If the command does not require data to be passed,
// this object can be set to null.
void Execute(object parameter);

How can I use a routed command on the view from a view model

I am trying to use a RoutedCommand on my view so that I can use the CanExecute functionality, but the only way I can get it to work is with a DelegateCommand from Prism. When I try to use the RoutedCommand the button stays inactive and the CanExecute function never gets used.
I've tried putting a CommandBinding on my XAML but that gives a "Only instance methods on the generated or code-behind class are valid." error. Here is that code:
<Window.CommandBindings>
<CommandBinding Command="AddCommand"
Executed="my:SettingsDialogViewModel.AddCommandMethod"
CanExecute="my:SettingsDialogViewModel.AddCommandMethodCanExecute" />
</Window.CommandBindings>
I've also tried setting up a CommandBinding in code, but that doesn't help either. I'm just not sure how to get it to work, short of sticking it in the code-behind, or implementing some ridiculously complicated looking thing I've found on the web.
Thanks for any help :)
EDIT:
Here are the methods I am trying to use:
public void AddCommandMethod()
{
if (SelectedMain != null)
{
SelectedMain.IsDirty = true;
_faveAppList.Add(SelectedMain);
SelectedMain.ListOrder = _faveAppList.Count;
_mainAppList.Remove(SelectedMain);
_listDirty = true;
}
}
public void AddCommandMethodCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
That isn't the proper MVVM notation. I'll provide one way of doing this.
// MyView.cs
public class MyView : UserControl
{
public MyViewViewModel ViewModel
{
get { return (MyViewViewModel) DataContext;}
set { DataContext = value; }
}
}
// DelegateCommand.cs
public class DelegateCommand : ICommand
{
private readonly Predicate<object> _canExecute;
private readonly Action<object> _execute;
public DelegateCommand(Action<object> execute)
: this(execute, null) {}
public DelegateCommand(Action<object> execute, Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
public override bool CanExecute(object parameter)
{
if (_canExecute == null)
{
return true;
}
return _canExecute(parameter);
}
public override void Execute(object parameter)
{
_execute(parameter);
}
}
// MyViewViewModel.cs
public class MyViewViewModel
{
public ICommand AddCommand {get;set;}
public MyViewViewModel()
{
AddCommand = new DelegateCommand (AddCommandMethod, AddCommandMethodCanExecute);
}
private void AddCommandMethod (object parameter)
{
}
private bool AddCommandMethodCanExecute(object parameter)
{
// Logic here
return true;
}
}
// MyView.xaml
<Button Command="{Binding AddCommand}" />
A better option would be to implement the ICommand interface and write your logic in the implemented methods. Then your view model can return your custom command and you could just bind to it from your view.
This will separate the actual command implementation from your view model but you can still nicely implement the logic within your view model.
Something like this:
public abstract class BaseCommand : ICommand
{
// needed to connect to WPF's commanding system
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public abstract bool CanExecute(object parameter);
public abstract void Execute(object parameter);
}
public class AddCommand : BaseCommand
{
private readonly MyViewModel _vm;
public AddCommand(MyViewModel vm)
{
this._vm = vm;
}
public override bool CanExecute(object parameter)
{
// delegate back to your view model
return _vm.CanExecuteAddCommand(parameter);
}
public override void Execute(object parameter)
{
_vm.ExecuteAddCommand(parameter);
}
}
public class MyViewModel
{
public ICommand AddCommand { get; private set; }
public MyViewModel()
{
AddCommand = new AddCommand(this);
}
public bool CanExecuteAddCommand(object parameter)
{
}
public void ExecuteAddCommand(object parameter)
{
}
}
Then just bind controls that issues the command.
<Button Command="{Binding AddCommand}">...</Button>

Categories

Resources