[英]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 = "";
}
}
}
另請注意項目參考。
您的問題的答案取決於您實例化SettingsViewModel
和ServiceOne
類的方式和位置。
最簡單的情況是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.