Pass value from ViewModel in one project into property located in another project

Viewed 49

I have property SettingValue in SettingsViewModel.cs located in project ExampleApp that I would like to use as setting and in case it changes, I would like to pass it as a property (DeviceName) into another Class named ServiceOne.cs that is located in another project ExampleApp.Service.

I would like to know solution without using MessagingCenter. MessagingCenter is available only for Xamarin. I want to understand how this should be done in general so I can utilize it also for example in WPF and other.

According to my research I need to create a new project with interface and use it for passing value from SettingsViewModel.cs to ServiceOne.cs? However I cant figure out how it can be done. Any hints?

SettingsViewModel.cs:

using ExampleApp.Views;
using Xamarin.Forms;

namespace ExampleApp.ViewModels
{
  public class SettingsViewModel : BaseViewModel
  {
    public SettingsViewModel()
    {
      Title = "Browse";
    }

    private string settingValue;
    public string SettingValue
    {
      get => this.settingValue;
      set
      {
        this.settingValue = value;
        this.OnPropertyChanged();
      }
    }
  }
}

ServiceOne.cs:

namespace ExampleApp.Service
{
  public class ServiceOne
  {
    public string DeviceName { get; set; }

    private void OnDeviceDiscovered()
    {
      this.DeviceName = "";
    }
  }
}

Please notice also project references.

enter image description here

1 Answers

The answer to your question depends on how and where you instantiate SettingsViewModel and ServiceOne classes.
The simplest case is when the SettingsViewModel creates an instance of ServiceOne.


    private readonly ServiceOne serviceOne = new();
    public string SettingValue
    {
      get => serviceOne.DeviceName;
      set
      {
        serviceOne.DeviceName = value;
        OnPropertyChanged();
      }
    }
  }

Very often, such instances are created at higher levels (for example, in App). In this case, you need to inject dependencies.

  public class SettingsViewModel : BaseViewModel
  {
    public SettingsViewModel(ServiceOne serviceOne)
    {
      Title = "Browse";
      this.serviceOne = serviceOne ?? ?? throw new ArgumentNullException(nameof(serviceOne));
    }

    private readonly ServiceOne serviceOne;
    public string SettingValue
    {
      get => serviceOne.DeviceName;
      set
      {
        serviceOne.DeviceName = value;
        OnPropertyChanged();
      }
    }
  }

Somewhere in App.Startup:

    ServiceOne serviceOne = new(); // Save in field
    SettingsViewModel settingsVM = new(serviceOne); 
Related