Implementing a custom WPF Command - c#

I wanted to implement a custom WPF command and I searched and found the following code:
public static class CustomCommands
{
public static readonly RoutedUICommand Exit = new RoutedUICommand
(
"Exit",
"Exit",
typeof(CustomCommands),
new InputGestureCollection()
{
new KeyGesture(Key.F4, ModifierKeys.Alt)
}
);
//Define more commands here, just like the one above
}
There are two things that I can't figure out.
Is it necessary to have commands static readonly? Cant we just declare it using const?
What exactly new InputGestureCollection() { new KeyGesture(Key.F4, ModifierKeys.Alt) } is? If it is calling default constructor and initializing properties so there should be a property to be assigned to, but there is nothing to be assigned. InputGestureCollection has braces, but inside braces it is not initialing any properties. How? What is this type of statement?

First of all, you need to get some basic understanding of WPF with MVVM.
You have a class that you are going to bind to your UI. That class is not the .xaml.cs
It is completely independent of the View. You need to put an instance of the class into the DataContext of the Window you can do this in the .xaml.cs by calling sth like that:
this.DataContext = new MyViewModel();
Now your class MyViewModel needs a Property of type ICommand.
Best practice is to make a class that implements ICommand. Normally you call it DelegateCommand or RelayCommand.
Example:
public class DelegateCommand : ICommand
{
private readonly Predicate<object> _canExecute;
private readonly Action<object> _execute;
public event EventHandler CanExecuteChanged;
public DelegateCommand(Action<object> execute)
: this(execute, null)
{
}
public DelegateCommand(Action<object> execute,
Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
if (_canExecute == null)
{
return true;
}
return _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute(parameter);
}
public void RaiseCanExecuteChanged()
{
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, EventArgs.Empty);
}
}
}
Then in your ViewModel you create a property with an Instance of that class in it. Like that:
public class MyViewModel{
public DelegateCommand AddFolderCommand { get; set; }
public MyViewModel(ExplorerViewModel explorer)
{
AddFolderCommand = new DelegateCommand(ExecuteAddFolderCommand, (x) => true);
}
public void ExecuteAddFolderCommand(object param)
{
MessageBox.Show("this will be executed on button click later");
}
}
In your view you can now bind the command of a button to that property.
<Button Content="MyTestButton" Command="{Binding AddFolderCommand}" />
A routed command is something that already exists in the framework by default (copy, paste etc). If you're a beginner to MVVM you shouldn't be thinking of creating routed commands before you get the basic understanding of "normal" commands.
To answer your first question: It is absolutely not nessesary to make Commands static and/or const. (See class MyViewModel)
Your 2nd question: You can initialize Lists with default values that you put into the {-brackets.
Example:
var Foo = new List<string>(){ "Asdf", "Asdf2"};
You don't have a object you initialize properties of. You have a list you initialize and then the Add() is called with the parameters you put in the {-brackets.
That's what basicly happens in your case too. You have a collection that you initialize with some values.

To answer your second question:
new InputGestureCollection()
{
new KeyGesture(Key.F4, ModifierKeys.Alt)
}
This is an example of a collection initializer and is equivalent to:
var collection = new InputGestureCollection();
collection.Add(new KeyGesture(Key.F4, ModifierKeys.Alt));
It's just a shorthand, and something that ReSharper suggests.

Related

UWP. How to pass command-parameter when ItemClickCommand of AdaptiveGridView executes?

<uwpkit:AdaptiveGridView ItemsSource="{x:Bind ViewModel.FavoriteContacts}"
IsItemClickEnabled="True"
SelectedItem="{x:Bind ViewModel.SelectedContact,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
ItemClickCommand="{x:Bind ViewModel.ExecuteCommand}">
</uwpkit:AdaptiveGridView>
This AdaptiveGridView show list of favorite contacts and instead of handling event ItemClick I choosed to use command. Furthermore I need to pass selected contact as command parametr. So I have found ItemClickCommand property that can help me use command. But I have not found any way that will allow me pass command parameter.
I tried to solve this problem with creating property SelectedContact and bind it to SelectedItem property of AdaptiveGridView but barrier that don't allow me to use this scenario is that execution of command runs before SelectedContact setter accessor runs. And I have null reference exception thrown.
So it was my only idea how to solve this task. If you know how to solve this task or maybe how to change order of executions of command and setter accessor of SelectedItem explain this.
First of all, It’s not very clear about “This AdaptiveGridView show list of favorite contacts and instead of handling event ItemClick I choosed to use command”. Does it mean “show list of favorite contacts” is only the itemsSource or when you handle ItemClick event, “the list of favorite contacts” will change?
But about “pass selected contact as command parameter”,you can read the following code:
First,in XAML:
<uwpkit:AdaptiveGridView ItemsSource="{x:Bind ViewModel.FavoriteContacts}"
IsItemClickEnabled="True"
ItemClickCommand="{x:Bind ViewModel. ExecuteCommand}">
Next,you can create command class like this:
public class RelayCommand : ICommand
{
public Contact selectedContact;
private readonly Action _execute;
private readonly Func<bool> _canExecute;
public event EventHandler CanExecuteChanged;
public RelayCommand(Action execute)
: this(execute, null)
{
}
public RelayCommand(Action execute, Func<bool> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute();
}
public void Execute(object parameter)
{
selectedContact = parameter as Contact;
_execute();
}
public void RaiseCanExecuteChanged()
{
var handler = CanExecuteChanged;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
Then,in your ViewModel,you can Initialize the command class as a property:
public RelayCommand ExecuteCommand { get; set; }
,this property is binded to “ItemClickCommand” in XAML.Also,you can initialize the ExecuteCommand and pass the MyItemClick event to the command:
public ContactViewModel() { ExecuteCommand = new RelayCommand(MyItemClick); }
in your ViewModel’s constructor.
Last,you can see the command has a “public void Execute(object parameter)” method . It has one parameter, which can be used to pass the information binded with the UIElement from the caller to the command. It means when you click the item,it will be triggered and the “Contact” object will be passed by this method.Then you can save it.So,when you click the item,the “MyItemClick” method will be triggered and you can use the Contact object you saved in the Execute method,for example:
private void MyItemClick(){
Contact contact = ExecuteCommand.selectedContact;
//do something when clicked
}
If you still have the problem, please share more details about your code, like a reproduce-able demo.

ICommand with Parameter

I found this: Close Window from ViewModel which gets me started down the path of modifying my DelegateCommand class to handle parameters. But I am not able to get the syntax worked out.
Here is my DelegateCommand class, and the DelegateCommand class that I'm trying to create with little success:
public 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;
}
#pragma warning disable 67
public event EventHandler CanExecuteChanged { add { } remove { } }
#pragma warning restore 67
}
public class DelegateCommand<T> : ICommand
{
private readonly Action _action;
public DelegateCommand(Action action)
{
_action = action;
}
public void Execute(object parameter)
{
_action();
}
public bool CanExecute(object parameter)
{
return true;
}
#pragma warning disable 67
public event EventHandler CanExecuteChanged { add { } remove { } }
#pragma warning restore 67
}
And here is what I do in the viewmodel:
public ICommand RowEditEndingAction
{
get { return new DelegateCommand(RowEditEnding); }
}
public ICommand UpdateDatabaseClick
{
get { return new DelegateCommand<object>(UpdateDatabase); } //THIS LINE HAS THE ERROR
}
And the actual method that will get called:
public void UpdateDatabase(object parameter)
{
Window w = (Window)parameter;
// A bunch of stuff that works is removed for brevity
w.Close();
}
The compiler does not like my UpdateDatabaseClick, specifically saying there is something wrong with the arguments to DelegateCommand, but I am at a loss as to what I am doing wrong (though I am thinking it is syntax . . . ). What do I need to change? This all worked before I added the parameter to UpdateDatabase, and just had the DelegateCommand (no template class). But in that case I could not close the window.
Here's the constructor of your DelegateCommand<T> class that you are calling:
public DelegateCommand(Action action)
And here is how you call it:
new DelegateCommand<object>(UpdateDatabase)
In there, UpdateDatabase is declared as follows:
public void UpdateDatabase(object parameter)
Now, the constructor you are invoking expects an Action. That is a parameterless method without a return value.
However, you are passing in a method with one parameter. That is what the compiler complains about.
What you actually probably want to do is to accept any method with one parameter - for that, you can use the type Action<T>. As your parameter should presumeably have the same type that is passed as a type argument to your DelegateCommand<T> class, you can declare your constructor like this:
public DelegateCommand(Action<T> action)
Now, you also need to update the type of your backing field where you store the action:
private readonly Action<T> _action;
Lastly, as _action now expects an argument, you need to pass that argument when invoking _action in DelegateCommand<T>.Execute. Normally, you want to hand over the parameter object you receive as an argument to the Execute method. However, that value is always typed to object, whereas you want to work with a strongly-typed value of type T in your method. Therefore, you will also have to add an additional cast:
public void Execute(object parameter)
{
_action((T)parameter);
}
I suggest you try Prism framework. It has all the component, tools, you need to work with WPF application with MVVM model.

WPF Simple Commanding Example

I try not to post questions like this, but i've really been struggling to find an answer or similar example. I have what I think is a really simple example I'd like to setup.
Basically I want to use commanding to add an item from a textbox to a listbox. I want to make sure there is something in the textbox via CanExecute and i want to make sure that its not already in the list.
I know this seems over complicated for what it is, but it hits on some points I've been struggling with.
<Window x:Class="Commanding_Example.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local ="clr-namespace:Commanding_Example"
Title="MainWindow" Width="200" Height="300">
<Window.DataContext>
<local:MainViewModel/>
</Window.DataContext>
<StackPanel>
<TextBlock>Name</TextBlock>
<TextBox></TextBox>
<Button>Add</Button>
<Button>Remove</Button>
<ListBox ItemsSource="{Binding People}" DisplayMemberPath="Name"></ListBox>
</StackPanel>
</Window>
I have a Person Class
class Person
{
public string Name { get; set; }
}
The only reason I have this is that the Add needs to create a new object, so slightly more complex than a simple string.
And then a basic view model
class MainViewModel : INotifyPropertyChanged
{
public MainViewModel()
{
People = new ObservableCollection<Person>();
People.Add( new Person {Name = "jimmy"});
}
public ObservableCollection<Person> People { get; set; }
#region Default INotifyPropertyChanged implimentation
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
So the question is, how would I implement commanding so that it uses the CanExecute to disable the Add button if the name is already there or the Name field is empty.
And then the same deal for Remove, only enabled if a name is selected in the list.
I'd like to make this as MVVM compliment as possible.
I've seen that you can do the Button.CommandBindings attached property to inject the methods you'd like to use for each, but that doesnt seem completely MVVM happy.
Also, i'd like to avoid the use of frameworks (Prism/Caliburn.Micro) since this is primarily for education reasons.
Also any references would be greatly appreciated. I've read many blogs etc but I always feel like they stray off before implementing a complete, simple example.
how would I implement commanding so that it uses the CanExecute to
disable the Add button if the name is already there or the Name field
is empty
I will show how to do the add, the remove is similar and I leave that for you to figure out. First I will show the xaml changes with the button using an AddPerson command:
<TextBox Text="{Binding CurrentPerson,
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged
}"/>
<Button Command="{Binding AddPerson}">Add</Button>
We have bound the current edited text to a new property on the View Model named CurrentPerson. This is done because we want to access what the person enters, but also we need the binding updated as the user types. To accomplish that updating, we specify that the binding updates by setting the UpdateSourceTrigger attribute to be PropertyChanged. Otherwise our the CurrentPerson string and ultimately the command Can operation would only fire when the edit text box lost focus.
ViewModel
The viewmodel will subscribe to the AddPerson command. Execution of that will add the user, but also check a can method which returns a boolean whether to enable the button or not. The can will be excecuted when the CurrentPerson property changes where we ultimately call RaiseCanExecuteChanged on the commanding class to have the button check the can method.
(This VM is abbreviated for the example and based on your full VM)
public OperationCommand AddPerson { get; set; }
public string _currentPerson;
public MainViewModel()
{
People = new ObservableCollection<Person>();
People.Add(new Person { Name = "jimmy" });
// First Lamda is where we execute the command to add,
// The second lamda is the `Can` method to enable the button.
AddPerson = new OperationCommand((o) => People.Add(new Person { Name = CurrentPerson }),
(o) => (!string.IsNullOrWhiteSpace(CurrentPerson) &&
!People.Any(per => per.Name == CurrentPerson)));
// When the edit box text changes force a `Can` check.
this.PropertyChanged += MainViewModel_PropertyChanged ;
}
void MainViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "CurrentPerson")
AddPerson.RaiseCanExecuteChanged();
}
Finally here is the commanding class used which is based on my blog article Xaml: ViewModel Main Page Instantiation and Loading Strategy for Easier Binding.:
public class OperationCommand : ICommand
{
#region Variables
Func<object, bool> canExecute;
Action<object> executeAction;
public event EventHandler CanExecuteChanged;
#endregion
#region Properties
#endregion
#region Construction/Initialization
public OperationCommand(Action<object> executeAction)
: this(executeAction, null)
{
}
public OperationCommand(Action<object> executeAction, Func<object, bool> canExecute)
{
if (executeAction == null)
{
throw new ArgumentNullException("Execute Action was null for ICommanding Operation.");
}
this.executeAction = executeAction;
this.canExecute = canExecute;
}
#endregion
#region Methods
public bool CanExecute(object parameter)
{
bool result = true;
Func<object, bool> canExecuteHandler = this.canExecute;
if (canExecuteHandler != null)
{
result = canExecuteHandler(parameter);
}
return result;
}
public void RaiseCanExecuteChanged()
{
EventHandler handler = this.CanExecuteChanged;
if (handler != null)
{
handler(this, new EventArgs());
}
}
public void Execute(object parameter)
{
this.executeAction(parameter);
}
#endregion
}
Well, MVVM is just a pattern or philosophy, so I think your desire to avoid using a framework might be a little misguided. Even if you're not using one of those frameworks, you will essentially be writing your own framework in order to implement the MVVM pattern.
That being said, probably what you want to use is a DelegateCommand or one of the similar implementations. See: http://www.wpftutorial.net/DelegateCommand.html. The important part that I think you are looking for is that the command that the WPF button is binding to must raise the CanExecuteChanged event whenever there is a change made in the view model which affects whether the command can or cannot be executed.
So in your case, for example, you would want to add a call to the CanExecuteChanged of your AddPersonDelegateCommand to your OnPropertyChanged method (possibly filtered by the name of the property that was changed). This tells anything bound to the command to call CanExecute on the command, and then you would have your logic in that CanExecute that actually determines if a person with the entered name already exists.
So to add some sample code, it might look something like this:
class MainViewModel : INotifyPropertyChanged
{
public MainViewModel()
{
People = new ObservableCollection<Person>();
People.Add( new Person {Name = "jimmy"});
AddPersonDelegateCommand = new DelegateCommand(AddPerson, CanAddPerson);
}
// Your existing code here
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
if(propertyName == "NewNameTextBox") AddPersonDelegateCommand.RaiseCanExecuteChanged();
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
public DelegateCommand AddPersonDelegateCommand { get; set; }
public void AddPerson()
{
// Code to add a person to the collection
}
public bool CanAddPerson()
{
return !People.Any(p=>p.Name == NewNameTextBox);
}
public string NewNameTextBox
{
get { return _newNameTextBox; }
set
{
_newNameTextBox = value;
OnPropertyChanged();
}
}
}
*Note: In this sample your <TextBox></TextBox> would need to be bound to the NewNameTextBox property on the view model.

Setting Property in Data Context from Action/Command

I have a DataTrigger in my XAML which is binded to a Property, 'ShowEffect' in my ViewModel class. I also have a button which is binded to a RelayCommand (class shown below) that calls a method. In that method, I set 'ShowEffect' to true. However, the DataTrigger does not seem to respond; the effect is not shown:
I declare the Property using:
private Boolean _ShowEffect;
public Boolean ShowEffect
{
get { return _ShowEffect; }
set { _ShowEffect = value; }
}
RelayCommand Class:
public class RelayCommand : ICommand
{
public RelayCommand(Action<object> execute)
: this(execute, null)
{
}
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
_execute(parameter);
}
private readonly Action<object> _execute;
private readonly Predicate<object> _canExecute;
}
I'm wondering whether the issue is related to the dispatcher. Can anyone suggest why the binding isn't working when I set the property in the method called by the command? It works when I set the property anywhere else in the ViewModel.
Converting previous comment to an answer.
your VM needs to implement INPC if it doesn't already and ShowEffect needs to Raise the propertychanged handler when it's changed(from it's setter when value changes) for changes made to it to be recognized by the View. What you got right now is a simple property which will not notify view of any updates made to it which is prolly what's happening when the command changes it's value but the view never gets to know about the change and your DataTrigger seems to not work.
INotifyPropertyChanged interface is what informs the View a property in the VM has changed. Hence your property needs to raise the PropertyChanged handler for it to thereby inform the view of any changes made to it.

Can I call a command inside a command?

I have a closecommand defined inside my viewmodel for my dialog window. I have another command defined inside that viewmodel. Now I have that command binded to a control in my view. After performing certain command actions, I want it to call closecommand to close the window. Is that possible?
Yes. You can use a CompositeCommand that wraps both (or any number) of your other commands. I believe this is in Prism, but if you don't have access to that in your project, it isn't terribly difficult to implement similar functionality on your own, especially if you're not using parameters - all you do is implement ICommand with a class and then have a private List of ICommands inside the class.
Here's more on the CompositeCommand class from Prism:
http://msdn.microsoft.com/en-us/library/microsoft.practices.composite.presentation.commands.compositecommand_members.aspx
My own admittedly short and possibly non-canonical implementation follows. To use it, all you need to do is have this be referenced on your VM, and then bind to it instead. You can call .AddCommand for all the other commands that you want to run. Probably the Prism one is implemented differently, but I believe this will work:
public class CompositeCommand : ICommand {
private List<ICommand> subCommands;
public CompositeCommand()
{
subCommands = new List<ICommand>();
}
public bool CanExecute(object parameter)
{
foreach (ICommand command in subCommands)
{
if (!command.CanExecute(parameter))
{
return false;
}
}
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
foreach (ICommand command in subCommands)
{
command.Execute(parameter);
}
}
public void AddCommand(ICommand command)
{
if (command == null)
throw new ArgumentNullException("Yadayada, command is null. Don't pass null commands.");
subCommands.Add(command);
}
}

Categories