XAML 将值从一个项目中的ViewModel传递到位于另一个项目中的属性

uoifb46i  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(198)

我在项目ExampleApp中的SettingsViewModel.cs中有属性SettingValue,我想将其用作设置,如果它发生变化,我想将其作为属性(DeviceName)传递到位于另一个项目ExampleApp.Service中的另一个名为ServiceOne.cs的类中。
我想知道不使用消息中心的解决方案。消息中心只对Xamarin可用。我想了解一般情况下应该如何做,这样我就可以在WPF和其他地方使用它。
根据我的研究,我需要创建一个新的项目与接口,并使用它传递值从SettingsViewModel.csServiceOne.cs?但我不知道如何可以做到这一点。任何提示?

设置视图模型.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();
      }
    }
  }
}

服务一个.cs:

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

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

还请注意项目参考。

wecizke3

wecizke31#

问题的答案取决于示例化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();
      }
    }
  }

应用程序启动中的某个位置:

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

相关问题