Command to call a method from viewmodel

OK, I try to avoid using commands because they always manage to confuse me, but I am in a new project and I am trying to archive it correctly, without code in my view. Basically, all I'm trying to do right now is to connect a button that launches a command that does some things on my presentation model, and for some reason something so simple still causes me problems. I think I'm close, but I can’t get there. Here is what I have right now.

<Window.Resources>
    <RoutedUICommand x:Key="GetMusic" />
</Window.Resources>
<Window.DataContext>
    <core:ViewMain />
</Window.DataContext>
<Window.CommandBindings>
    <CommandBinding Command="{StaticResource GetMusic}" Executed="GetMusicExecuted"/>
</Window.CommandBindings>

And the view model has almost nothing right now

public class ViewMain
{
    public MusicCollection Music { get; set; }

    private void GetMusicExecuted(object sender, ExecutedRoutedEventArgs e)
    {
        //Logic
    }
}

, , , , execute , . , , ? , , .

+5
1

, ICommand. Button Command command . , Execute, Command.

, , Command, , , .

ViewModel:

public class MyViewModel
{
    public MyCommand ActionCommand
    {
        get;
        set;
    }

    public MyViewModel()
    {
        ActionCommand = new MyCommand();
        ActionCommand.CanExecuteFunc = obj => true;
        ActionCommand.ExecuteFunc = MyActionFunc;
    }

    public void MyActionFunc(object parameter)
    {
        // Do stuff here 
    }

}

public class MyCommand : ICommand 
{
    public Predicate<object> CanExecuteFunc
    {
        get;
        set;
    }

    public Action<object> ExecuteFunc
    {
        get;
        set;
    }

    public bool CanExecute(object parameter)
    {
        return CanExecuteFunc(parameter);
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        ExecuteFunc(parameter);
    }
}

( , DataContext ):

<Window x:Class="exp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Command="{Binding Path=ActionCommand}">Action</Button>
    </Grid>
</Window>
+11

All Articles