c#
Button doesn't execute command MVVM WPF
I have problem with binded command to the button. I cannot execute this command on click, but this code worked fine in few other places. I'm using MVVM Light Toolkit. Here is DataContext binding and button code. DataContext="{Binding Source={StaticResource Locator}, Path=UserTodoViewModel}" <Button HorizontalAlignment="Center" Margin="5" Background="Gray" Foreground="White" Command="{Binding SaveCommand}" /> ViewModel: public ICommand SaveCommand { get; } SaveCommand = new RelayCommand( () => { // Some logic MessageBox.Show("Changes saved!", "Project Manager", MessageBoxButton.OK, MessageBoxImage.Information); }); Thanks for any help.
Your XAML Code is fine. But in the Viewmodel you need to edit your command handler. Try this: Create a class for command handler: 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(); } } In the Viewmodel use this command property: public ICommand SaveCommand { get { return new CommandHandler(() => Save(), true); } } In this way you can reuse the command handler class for another command, also you only one row of code to define the command property
When I've used MVVM Light in the past, here's how I've done button commands View Model: public RelayCommand SaveEmployeeCommand { get; private set; } // call this method from ctor private void InitializeCommands() { SaveEmployeeCommand = new RelayCommand( Save, () => true); } private void Save() { } Then in XAML: <Button Command="{Binding Path=SaveEmployeeCommand}">
Related Links
Exception related to relative paths
array parameter when overriden in method doesn't change outside of it
AES: Use nonce to create new key for HMAC
Xamarin Android aplication doesn't work without debugger
Load data from database to TreeView when parent and child are parts of the same field in C#
How to skip the creating the root node on a treeview?
Add or remove relations one-to-many entity doesn't work
ListBoxItems selected color differs when programatically selecting the item
Reusing the connection and prepare statement to mysql database
Play audio from a stream in UWP
EWS MVC where save message
lambda expression and the model keyword cannot be used in strongly typed views inside a class library [duplicate]
Return JSON data from webservice [duplicate]
.net standard doesn't resolve child assemblies
How do I constraint a generic type parameter to only accept nullable value types in C#?
Object reference not set to an instance of an object for my Database object. C# [duplicate]