Search code examples
c#mvvmuwpviewmodelwindows-community-toolkit

What is the best practice to implement methods using values of properties in the View Model?


I am currently developing a UWP application, but I think this question applies to any project type with a UI. I have built a View Model for my UI using the new Microsoft Toolkit MVVM library. It has properties such as:

        private bool _isLoginAvailable = true;     
        public bool IsLoginAvailable
        {
            get => _isLoginAvailable;
            set => SetProperty(ref _isLoginAvailable, value);
        }

Furthermore, I have a few business methods that as parameters require up to 5-6 of these properties.

Reading on forums, I saw that it is unadvised to business logic within the view model, therefore, I came up with the following options:

  1. Create a new class for the methods, and use the view model as a parameter: SampleMethod(SampleViewModel vm). Then, if I create an object of this class in the view model, I could use SampleMethod(this). At this point, I don't really see a difference between this option, and including the method within the view model class.
  2. Second option I see is to add each required parameter to the method, and return each parameter as well in a tuple: SampleMethod(var1, var2, var3...) { return (var1, var2, var3...)} This to me seems very cumbersome.
  3. The third option I figured is to use the MVVM Toolkit's messaging feature. In this case, I can set up the constructor of the view model to listen to messages with Messenger.Register<SampleViewModel, Var1Message>(this, (r, m) => r.var1 = m.Value);. Then, the method in a differenct class can send the value in message using Messenger.Send(new Var1Message(message). While this seems to be the best option, as it can be easily implemented together with dependency injection, it quickly becomes very convoluted, as for each property a new sealed class is required, that describes the message.

Is any of these options the best practice, or is there an option that I am not aware of?


Solution

  • If business methods require multiple properties in your VM, then maybe the properties should be in the business object? Are the properties intrinsic to the business rules, or do they only exist in the context of the view?

    VM properties can just pass through to the business properties, or quite often you can just directly expose the business object itself in your VM.