I'm developing WPF applications and I want to reuse my classes that are the same in all those applications so I can add them as a reference.
In my case I have a class for my Commands:
public class RelayCommand : ICommand
{
#region Fields
readonly Action<object> _execute;
readonly Predicate<object> _canExecute;
#endregion // Fields
#region Constructors
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;
}
#endregion // Constructors
#region ICommand Members
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);
}
#endregion // ICommand Members
}
This works perfect in my application, but when I want to make a class library which I just want to add as a reference in my project, visual studio can't build because "CommandManager does not exists in the current context". In my usings I have the following (which should be enough)
using System;
using System.Windows.Input;
Any ideas why I can't do this in a "class library project" ?
Go to the "References" part of your class library and select "Add Reference". Look for an assembly called "PresentationCore" and add it.
Then in your class file add the using statement using System.Windows.Input;
You will then be able to access the CommandManager as you expect.
Just adding: lots of guys when they go to create a class library, they select "WPF Custom Control Library" and then erase the "Class1.cs" file. It's a shortcut that automatically adds the right namespaces to your library. Whether it's a good or bad shortcut is anybody's call, but I use it all the time.
Related
I'm having some difficulty with Context Menu commands on my View Model.
I'm implementing the ICommand interface for each command within the View Model, then creating a ContextMenu within the resources of the View (MainWindow), and using a CommandReference from the MVVMToolkit to access the current DataContext (ViewModel) Commands.
When I debug the application, it appears that the CanExecute method on the command is not being called except at the creation of the window, therefore my Context MenuItems are not being enabled or disabled as I would have expected.
I've cooked up a simple sample (attached here) which is indicative of my actual application and summarised below. Any help would be greatly appreciated!
This is the ViewModel
namespace WpfCommandTest
{
public class MainWindowViewModel
{
private List<string> data = new List<string>{ "One", "Two", "Three" };
// This is to simplify this example - normally we would link to
// Domain Model properties
public List<string> TestData
{
get { return data; }
set { data = value; }
}
// Bound Property for listview
public string SelectedItem { get; set; }
// Command to execute
public ICommand DisplayValue { get; private set; }
public MainWindowViewModel()
{
DisplayValue = new DisplayValueCommand(this);
}
}
}
The DisplayValueCommand is such:
public class DisplayValueCommand : ICommand
{
private MainWindowViewModel viewModel;
public DisplayValueCommand(MainWindowViewModel viewModel)
{
this.viewModel = viewModel;
}
#region ICommand Members
public bool CanExecute(object parameter)
{
if (viewModel.SelectedItem != null)
{
return viewModel.SelectedItem.Length == 3;
}
else return false;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
MessageBox.Show(viewModel.SelectedItem);
}
#endregion
}
And finally, the view is defined in Xaml:
<Window x:Class="WpfCommandTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfCommandTest"
xmlns:mvvmtk="clr-namespace:MVVMToolkit"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<mvvmtk:CommandReference x:Key="showMessageCommandReference" Command="{Binding DisplayValue}" />
<ContextMenu x:Key="listContextMenu">
<MenuItem Header="Show MessageBox" Command="{StaticResource showMessageCommandReference}"/>
</ContextMenu>
</Window.Resources>
<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>
<Grid>
<ListBox ItemsSource="{Binding TestData}" ContextMenu="{StaticResource listContextMenu}"
SelectedItem="{Binding SelectedItem}" />
</Grid>
</Window>
To complete Will's answer, here's a "standard" implementation of the CanExecuteChanged event :
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
(from Josh Smith's RelayCommand class)
By the way, you should probably consider using RelayCommand or DelegateCommand : you'll quickly get tired of creating new command classes for each and every command of you ViewModels...
You have to keep track of when the status of CanExecute has changed and fire the ICommand.CanExecuteChanged event.
Also, you might find that it doesn't always work, and in these cases a call to CommandManager.InvalidateRequerySuggested() is required to kick the command manager in the ass.
If you find that this takes too long, check out the answer to this question.
Thank you for the speedy replies. This approach does work if you are binding the commands to a standard Button in the Window (which has access to the View Model via its DataContext), for example; CanExecute is shown to be called quite frequently when using the CommandManager as you suggest on ICommand implementing classes or by using RelayCommand and DelegateCommand.
However, binding the same commands via a CommandReference in the ContextMenu
do not act in the same way.
In order for the same behaviour, I must also include the EventHandler from Josh Smith's RelayCommand, within CommandReference, but in doing so I must comment out some code from within the OnCommandChanged Method. I'm not entirely sure why it is there, perhaps it is preventing event memory leaks (at a guess!)?
public class CommandReference : Freezable, ICommand
{
public CommandReference()
{
// Blank
}
public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(CommandReference), new PropertyMetadata(new PropertyChangedCallback(OnCommandChanged)));
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
#region ICommand Members
public bool CanExecute(object parameter)
{
if (Command != null)
return Command.CanExecute(parameter);
return false;
}
public void Execute(object parameter)
{
Command.Execute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
CommandReference commandReference = d as CommandReference;
ICommand oldCommand = e.OldValue as ICommand;
ICommand newCommand = e.NewValue as ICommand;
//if (oldCommand != null)
//{
// oldCommand.CanExecuteChanged -= commandReference.CanExecuteChanged;
//}
//if (newCommand != null)
//{
// newCommand.CanExecuteChanged += commandReference.CanExecuteChanged;
//}
}
#endregion
#region Freezable
protected override Freezable CreateInstanceCore()
{
throw new NotImplementedException();
}
#endregion
}
However, binding the same commands via a CommandReference in the
ContextMenu do not act in the same way.
That's a bug in CommandReference implementation. It follows from these two points:
It is recommended that the implementers of ICommand.CanExecuteChanged hold only weak references to the handlers (see this answer).
Consumers of ICommand.CanExecuteChanged should expect (1) and hence should hold strong references to the handlers they register with ICommand.CanExecuteChanged
The common implementations of RelayCommand and DelegateCommand abide by (1). The CommandReference implementation doesn't abide by (2) when it subscribes to newCommand.CanExecuteChanged. So the handler object is collected and after that CommandReference no longer gets any notifications that it was counting on.
The fix is to hold a strong ref to the handler in CommandReference:
private EventHandler _commandCanExecuteChangedHandler;
public event EventHandler CanExecuteChanged;
...
if (oldCommand != null)
{
oldCommand.CanExecuteChanged -= commandReference._commandCanExecuteChangedHandler;
}
if (newCommand != null)
{
commandReference._commandCanExecuteChangedHandler = commandReference.Command_CanExecuteChanged;
newCommand.CanExecuteChanged += commandReference._commandCanExecuteChangedHandler;
}
...
private void Command_CanExecuteChanged(object sender, EventArgs e)
{
if (CanExecuteChanged != null)
CanExecuteChanged(this, e);
}
In order for the same behaviour, I must also include the EventHandler
from Josh Smith's RelayCommand, within CommandReference, but in doing
so I must comment out some code from within the OnCommandChanged
Method. I'm not entirely sure why it is there, perhaps it is
preventing event memory leaks (at a guess!)?
Note that your approach of forwarding subscription to CommandManager.RequerySuggested also eliminates the bug (there's no more unreferenced handler to begin with), but it handicaps the CommandReference functionality. The command with which CommandReference is associated is free to raise CanExecuteChanged directly (instead of relying on CommandManager to issue a requery request), but this event would be swallowed and never reach the command source bound to the CommandReference. This should also answer your question as to why CommandReference is implemented by subscribing to newCommand.CanExecuteChanged.
UPDATE: submitted an issue on CodePlex
An easier solution for me, was to set the CommandTarget on the MenuItem.
<MenuItem Header="Cut" Command="Cut" CommandTarget="
{Binding Path=PlacementTarget,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ContextMenu}}}"/>
More info: http://www.wpftutorial.net/RoutedCommandsInContextMenu.html
<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.
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.
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.
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.