繁体   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