I draw UI using WPF and MVVM. Using

<Button Name="priceButton" Content="Прайс" Command="{Binding GetPricesCom}" HorizontalAlignment="Left" Margin="339,513,0,0" VerticalAlignment="Top" Width="125" Height="31" Click="priceButton_Click"/> 

The method is called when the program is started, and not when the button is pressed. How to implement ICommand so that it is called only when a button is pressed.

  public ICommand GetPricesCom { get { GetPrices(); return GetPricesCom; } } 
  • 1. Margin - do not put the elements in your hands in the constructor, learn the XAML markup and write everything yourself (otherwise you will ask the question "that my elements jump / disappear"). Margin itself should be no higher than 15-20, not 339 ... 2. The ICommand logic is implemented not in its get, but in a separate method, which is defined by this interface via RelayCommand. 3. Click and Command on the same control ... Are you serious? - EvgeniyZ
  • I first encountered WPF, but XAML was also not studied. I would be grateful if you advise high-quality literature on it. - Ivan
  • Could and search ... - EvgeniyZ

1 answer 1

Suppose you have a button

 <Button Content="Test" Margin="5" Command="{Binding TestCommand}"> 

Further, in your ViewModel you create a command. I use this solution:

This is the base class for teams, has found it for a long time and now it wanders from project to project.

 public class RelayCommand : ICommand { private Action<object> _execute; private Func<object, bool> _canExecute; public event EventHandler CanExecuteChanged { add => CommandManager.RequerySuggested += value; remove => CommandManager.RequerySuggested -= value; } public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null) { _execute = execute; _canExecute = canExecute; } public bool CanExecute(object parameter) { return _canExecute == null || _canExecute(parameter); } public void Execute(object parameter) { _execute(parameter); } } 

And in the ViewModel declare the command

 public RelayCommand TestCommand => new RelayCommand(o => { //Логика команды });