I am creating an application using the MVVM design pattern and I want to use the RoutedUICommands defined in the ApplicationCommands class. Since the CommandBindings property for View (read UserControl) is not a DependencyProperty, we cannot directly associate the CommandBindings defined in the ViewModel with the view. I solved this by defining an abstract View class that binds it programmatically, based on the ViewModel interface, which ensures that each ViewModel has ObservableCollection CommandBindings. All this works fine, however in some scenarios I want to execute the logic defined in different classes (View and ViewModel) by the same command. For example, when saving a document.
In ViewModel, the code saves the document to disk:
private void InitializeCommands()
{
CommandBindings = new CommandBindingCollection();
ExecutedRoutedEventHandler executeSave = (sender, e) =>
{
document.Save(path);
IsModified = false;
};
CanExecuteRoutedEventHandler canSave = (sender, e) =>
{
e.CanExecute = IsModified;
};
CommandBinding save = new CommandBinding(ApplicationCommands.Save, executeSave, canSave);
CommandBindings.Add(save);
}
, - , , TextBox , , , . , Ctrl + S. , , , . UpdateSourceTrigger PropertyChanged , - . , PreviewExecuted PreviewExecuted, :
//Find the Save command and extend behavior if it is present
foreach (CommandBinding cb in CommandBindings)
{
if (cb.Command.Equals(ApplicationCommands.Save))
{
cb.PreviewExecuted += (sender, e) =>
{
if (IsModified)
{
BindingExpression be = rtb.GetBindingExpression(TextBox.TextProperty);
be.UpdateSource();
}
e.Handled = false;
};
}
}
PreviewExecuted, , , Handled false. , executeSave, , . , cb.PreviewExecuted cb. do, .
, .Net, PreviewExecuted Executed , .
- ? ? ?