簡體   English   中英

將值從一個項目中的 ViewModel 傳遞到位於另一個項目中的屬性

[英]Pass value from ViewModel in one project into property located in another project

我在位於項目ExampleApp中的SettingsViewModel.cs中有屬性 SettingValue,我想將其用作設置,如果它發生變化,我想將其作為屬性 (DeviceName) 傳遞到另一個名為ServiceOne.cs的 Class 中項目ExampleApp.Service

我想知道不使用 MessagingCenter 的解決方案。 MessagingCenter 僅適用於 Xamarin。 我想了解一般應該如何做到這一點,所以我也可以在 WPF 等中使用它。

根據我的研究,我需要創建一個帶有接口的新項目並將其用於將值從SettingsViewModel.cs傳遞到ServiceOne.cs 但是我無法弄清楚它是如何完成的。 有什么提示嗎?

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 = "";
    }
  }
}

另請注意項目參考。

在此處輸入圖像描述

您的問題的答案取決於您實例化SettingsViewModelServiceOne類的方式和位置。
最簡單的情況是SettingsViewModel創建ServiceOne的實例。


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

很多時候,此類實例是在更高級別(例如,在 App 中)創建的。 在這種情況下,您需要注入依賴項。

  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();
      }
    }
  }

App.Startup 中的某處:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM