Silverlight Multiple Command Binding in MVVM
I am starting to build Silverlight application using MVVM. I have button on a XAML page to enable saving of data on its click I have written following code.
<Button Content="Save" Grid.Column="2" Grid.Row="3"
Command="{Binding Path=SaveCourse}"/>
and in the view model class i have implemnets the following code;
public class SaveCurrentCourse : ICommand
{
private MaintenanceFormViewModel viewModel;
public SaveCurrentCourse(MaintenanceFormViewModel viewModel)
{
this.viewModel = viewModel;
this.viewModel.PropertyChanged += (s, e) =>
{
开发者_开发百科 if (this.CanExecuteChanged != null)
{
this.CanExecuteChanged(this, new EventArgs());
}
};
}
public bool CanExecute(object parameter)
{
return this.viewModel.CurrentCourse != null;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
this.viewModel.SaveCourseImplementation();
}
}
Which kind of works for my save command. The question I have is if there are multiple buttons on the page then do I have to write the same code as above for each of the button? Can any body suggest a better way?
Microsoft's patterns & practices team offers a library called Prism that simplifies this somewhat. http://compositewpf.codeplex.com/
They provide a class called DelegateCommand
that implements ICommand
and allows you to pass the method name that you would like executed.
public class Test {
public Test(){
SomeCommand = new DelegateCommand<object>(DoSomething);
}
public DelegateCommand<object> SomeCommand { get; private set;}
private void DoSomething(object parameter){
//Do some stuff
}
}
You can then bind your controls Command property to SomeCommand
. You can also bind CommandParameter to something and it will be passed in as the parameter to the DoSomething method. An additional constructor for DelegateCommand allows you to pass a CanExecute method as a second parameter, that will enable/disable the control. If you need to update the enabled/disabled status of the control you can call DelegateCommand's RaiseCanExecuteChanged()
method.
public class Test {
public Test(){
SomeCommand = new DelegateCommand<object>(DoSomething, (enabled) => CanSave());
}
public DelegateCommand<object> SomeCommand { get; private set;}
private void DoSomething(object parameter){
//Do some stuff
}
private bool CanSave(){
if(/*test if the control should be enabled */)
return true;
else
return false;
}
private void DoABunchOfStuff(){
//something here means the control should be disabled
SomeCommand.RaiseCanExecuteChanged();
}
}
精彩评论