Binding two commands in one button WPF/MVVM

这一生的挚爱 提交于 2019-12-05 16:35:07

You want to click one Button and run two pieces of code... it really doesn't sound that complicated. Using one of the available RelayCommands, the problem could be fixed as simply as this:

public ICommand SomeCommand
{
    get { return new ActionCommand(action) => { RunFirstFunction(action); 
        RunSecondFunction(action) }, canExecute => someCondition); }
}

In XAML:

<Button Command="{Binding SomeCommand}" CommandParameter="{Binding SomeObject}">
    Click Me
</Button>

ActionCommand is my own form of the RelayCommand, but all of the delegate ICommand implementations are roughly equal and could work in this way. The CommandParameter value comes into the code as the action variable and is passed through to the two functions.

You could use the CompositeCommand from the Prism Framework. Create an additional CompositeCommand in your viewmodel, register both ordinary commands with this CompositeCommand and bind the button to the CompositeCommand.

See the Prism documentation on page 130 on how to work with CompositeCommands.

Your app needs to reference Microsoft.Practices.Prism.dll which is included in the Prism package.

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