Override non virtual bound method in viewmodel (AvaloniaUI)

29 views Asked by At

I have a core project with a login view and viewmodel, the assembly is published as nuget. Now in my custom project I want to change some behavior like for example the login.
So I created a CustomLoginView that contains the original LoginView and a CustomViewModel : LoginViewModel with a new Login() which hides the original one.

The problem is now there is still the original Login() called.

  • Is this because the binding in the core project was created on compiling and it goes on LoginViewModel.Login() explicitly?
  • If this is correct is it possible to for example to trigger reevaluate the bindings on current data context?

A workaround should be be to make the method virtual in the LoginViewModel.
Since I would like to have the core project customizable this would mean I have to make everything virtual. I would like to avoid this.

1

There are 1 answers

2
Tarazed On

The reason this happens is because hiding does not change the method in LoginView.

Consider the following:

class LoginView
{
  public void Login()
  {
    Console.WriteLine("This was called from LoginView");
  }
}

class CustomLoginView : LoginView
{
  public new void Login()
  {
    Console.WriteLine("This was called from CustomLoginView");
  }
}

If I were to create a CustomLoginView like so...

CustomLoginView view = new CustomLoginView();
view.Login();

The expected output would be This was called from CustomLoginView.

However if I did the following...

LoginView view = new CustomLoginView();
view.Login();

The output would instead be This was called from LoginView.

If you don't override a virtual then the method will not be replaced when called from the base class. The same is true if you cast to the base.

CustomLoginView view = new CustomLoginView();
((LoginView)view).Login();

The expected output would also be This was called from LoginView. Overriding a virtual is the only way to change this behavior. When you override a virtual, the behavior of the overriding method will persist in all of these cases.