Trigger a user control action from view model in Avalonia

151 views Asked by At

I am using the PanAndZoom conrol in an Avalonia 11 application. Unfortunately, it seems that the zoom reset of this control can be triggered by a control methode only.

Now I was wondering how to trigger the ResetMatrix action from the view model directly accordingly to the MVVM priciples.

Currently, I am calling this methode in the code-behind of the view:

public partial class VideoView : UserControl
{
    #region Public Constructors

    public VideoView()
    {
        InitializeComponent();

        var zoomBorder = this.FindControl<ZoomBorder>("VideoBorder");
        var dataContext = this.DataContext as VideoViewModel;

        if (dataContext != default
            && zoomBorder != default)
        {
            dataContext.OnVideoCentredEvent += (s, e) => zoomBorder.ResetMatrix();
        }
    }

    #endregion Public Constructors
}

I have found this answer already, but I was not able to adjust it to available dependency properties in Avalonia 11.

I am looking for a solution which most likely is based on a behaviour. But maybe there are other solutions too, which I haven't found yet.

1

There are 1 answers

0
Tarazed On BEST ANSWER

It's a common misconception that MVVM means "no code behind". MVVM means the view logic should only interact with the business logic through loose coupling (i.e. Communication in one direction and Events/Callbacks and passed through the ViewModel using INotifyPropertyChanged). The model should make no direct reference to the view or viewmodel, it lives in it's own little world and simply invokes events and callbacks. The view should make no direct reference to the model but can make direct reference to the viewmodel, and the view model should make no direct reference to the view but can make direct reference to the model. One way communications, and events to go backward.

What you have here is pure view logic that is being hooked up to an event in your View Model, this is conceptually not different than a binding. A binding is just a syntactic way to monitor a very specific event on the view model and reacting to it. The View registers for an event, the ViewModel has no direct reference to the View as MVVM dictates. What you have here is still within the MVVM pattern.

You could use Avalonia Behaviors, but to be honest, for this one little event hookup, that's overkill and it's going to make your code complicated, and there is nothing wrong with code behind as long it's following the MVVM pattern.