I need to bind a menuitem and a button. the menu item is 'start simulation'. As soon as this menu item is pressed the simulation starts and the menu item is checked. Now i have given an additional button 'play' in the toolbar which does exactly the same function. When it is pressed, the simulation starts and the button becomes disabled. I can check the menu item upon click and disable the play button upon click individually but don't know how to link the two button clicks.
1 Answers
If you haven't already pull your code that starts your simulation out into a separate method like this
private void StartSimulation()
{
...
}
Then create a click event for your button and your menu item and call your method from them.
private void button_Click(object sender, RoutedEventArgs e)
{
StartSimulation();
...
}
private void menuItem_Click(object sender, RoutedEventArgs e)
{
StartSimulation();
...
}
To disable your button you use
button.IsEnabled = false;
So to disable it while the simulation is running simply add it before you call StartSimulation
and then call
button.IsEnabled = true;
To re-enable it when the simulation is finished like this
private void button_Click(object sender, RoutedEventArgs e)
{
button.IsEnabled = false;
StartSimulation();
...
button.IsEnabled = true;
}
Note I've assumed you mean wpf since you've tagged the question as wpf.
Edit
If you'd like to do it using commands you probably want to implement ICommand something like this
public class RelayCommand : ICommand
{
private Predicate<object> _canExecute;
private Action<object> _execute;
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
this._canExecute = canExecute;
this._execute = execute;
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public bool CanExecute(object parameter)
{
return _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute(parameter);
}
}
Then you can use it like this
In your view model
public ICommand MyCommand { get; set; }
In your view model's constructor
MyCommand = new BaseCommand(_ =>
{
// Do your stuff here
});
Then, in your view, bind to it wherever you want to use your command
<Button Content="Click Me" Command="{Binding MyCommand}"/>
This tutorial gives a nice overview of commands and the answer to this question gives a slightly different implementation.

- 913
- 6
- 14
-
Thank you for the response. However i wanted to link the two buttons through binding so that i donot have to fumble with the code when things get further complicated as the gui proceeds. I have an idea of how to handle things with the code. what i wanted to know was how to use the binding expression. I am sorry i was not clear in my question i guess. – sadia_123k Jun 22 '17 at 04:37