What I have:
- using MVVM pattern
- a view written in XAML
- a command
MyCommand
in the ViewModel which gets called from several places in the view - a method
DoSthInView
that operates on the view, defined in codebehind
My Goal:
Whenever the command is executed, I want to call DoSthInView
, no matter which control executed the command.
Question:
Since in MVVM the ViewModel does not know the View, I cannot call DoSthInView
from the ViewModel. So how do call this code?
Own thoughts:
To be less abstract, this is my use case: We have one Button and one TextBox. The command takes the text which is currently in the TextBox and writes it somewhere into the model data. When this writing is done, I want to animate a green checkmark appearing and fading out (this is DoSthInView
), so that the user gets a visual confirmation that the data was updated.
There are two ways of running the command:
- Click the Button
- Press "Enter" while the TextBox is focused
For the Button I know a way to call DoSthInView
:
<Button Content="run command" Command="{Binding MyCommand}" Click={Binding DoSthInView}" />
For the TextBox, I have a KeyBinding to take the Enter key:
<TextBox>
<TextBox.InputBindings>
<KeyBinding Command="{Binding MyCommand}" Key="Enter" />
</TextBox.InputBindings>
</TextBox>
But InputBindings seem not to support events, only commands. So here I have no idea how to call DoSthInView
.
But even if I found a way to call DoSthInView
from within the input binding (analog to the Button), it wouldn't feel right. I am looking for a way to say "whenever MyCommand
is executed, run DoSthInView
" So that not every caller of MyCommand
has to care for it individually, but there is just one place to handle that. Maybe this can be done in the root FrameworkElement?