Let's see 2 examples:
Setting focus
For focus, we have to call method UIelement.Focus()
in code-behind, so standard approach in MVVM is to create *behaviour`:
public static class FocusedBehavior
{
public static bool GetIsFocused(DependencyObject obj)
{
return (bool)obj.GetValue(IsFocusedProperty);
}
public static void SetIsFocused(DependencyObject obj, bool value)
{
obj.SetValue(IsFocusedProperty, value);
}
public static readonly DependencyProperty IsFocusedProperty =
DependencyProperty.RegisterAttached("IsFocused", typeof(bool), typeof(FocusedBehavior), new UIPropertyMetadata(false, OnIsFocusedChanged));
private static void OnIsFocusedChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if((bool)e.NewValue)
(sender as UIElement).Focus();
}
}
Then for each control we want to be able to set focus we do
<Button ... local:FocusedBehavior.IsFocused="{Binding SomeDependencyProperty}"/>
where bool SomeDependencyProperty
has to be created in ViewModel for each control individually. This way ViewModel can change something in the View by setting value of its own property.
Controlling blur
To set blur (see here), we have to change property BlurEffect.Radius
. This can be as simple as
<Window.Effect>
<BlurEffect Radius="{Binding SomeDependencyProperty}"/>
</Window.Effect>
where int SomeProperty
is again has to be created in ViewModel personally for each case.
Question
Is there any more ways to change something in View by ViewModel?
I want to know all possibilities to be able to use the most appropriate. To set focus we have to use behaviour approach, to set blur simple binding. Are there more possibilities?
Very generic solution would be to let ViewModel know about View, so it can call methods and use properties when, to example, processing commands, but this is bad idea. Right? Though in this case View can be extended itself with public properties and methods to achieve some result (to example, set focus or set blur).