I have a button lives in View1. View1 has ViewModel1. I have a CheckBox that lives in View2. View2 has ViewModel2. Now if I wanted to use a button command to check the Checkbox (Note that the CheckBox IsChecked is already bound to something else). So just for practicing and try to make it work, I made a class called Commands like shown below. then I made another class called CommandsViewModel as shown below, that will be used by the button to show a MessageBox. Now how to make it check the CheckedBox to instead of showing the MessageBox.
Here is the Commands Class
public class Commands : ICommand
{
Action<object> executeMethod;
Func<object, bool> canExecuteMethod;
public Commands(Action<object> executeMethod, Func<object, bool> canExecuteMethod)
{
this.executeMethod = executeMethod;
this.canExecuteMethod = canExecuteMethod;
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
executeMethod(parameter);
}
public event EventHandler CanExecuteChanged;
}
Here is the CommadsViewModel Class
public class CommandsViewModel
{
public ICommand MyCommand { get; set; }
public CommandsViewModel()
{
MyCommand = new Commands(ExecuteMethod, canExecuteMethod);
}
private bool canExecuteMethod(object parameter)
{
return true;
}
private void ExecuteMethod(object parameter)
{
MessageBox.Show("Command executed!");
}
}
Here is the button
<Button Content="Select All"
Command="{Binding MyCommand, Source={StaticResource cmdvm}}"
MinWidth="150" Margin="0,5,20,20">
Here is the Checkbox
<CheckBox
Name="myCB"
Content="{Binding ItemName}"
IsChecked="{Binding ItemIsChecked}"/>
Aucun commentaire:
Enregistrer un commentaire