Command to call method from viewmodel

狂风中的少年 提交于 2019-12-05 11:18:48

I tend to use my own command class, implementing ICommand. Then I bind the Button Command property to the command property in my view model. When the button is clicked, it executes the Execute method whatever is bound to the Command property.

This is the ugly two minute version, but it shows how you can make a Command class and then assign it delegates that point back to whatever method you like on your view model.

The 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);
    }
}

The View would bind to it thusly (assuming DataContext is set to an instance of the view model):

<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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!