[英]Should I bind to SharedService property in WPF Prism
我使用SharedService(Prism)在兩個模塊之間獲取數據。 在SharedService中,我放置了一個名為AdapterName的字符串屬性。 假設模塊A中具有ViewAViewModel,模塊B中具有ViewBViewModel
public class ViewAViewModel : BindableBase {
private string _adapterNameA;
public string AdapterNameA
{
get { return _adapterNameA; }
set { SetValue (ref _adapterNameA, value); }
}
private ISharedService _sharedService;
public ISharedService SharedService {
get { return _sharedService; }
set { SetValue (ref _sharedService, value); }
}
public ViewAViewModel (ISharedService sharedService) {
_sharedService = sharedService;
}
}
public class ViewBViewModel : BindableBase {
private string _adapterNameB;
public string AdapterNameB {
get { return _adapterNameB; }
set { SetValue (ref _adapterNameB, value); }
}
private ISharedService _sharedService;
public ISharedService SharedService {
get { return _sharedService; }
set { SetValue (ref _sharedService, value); }
}
public ViewBViewModel (ISharedService sharedService) {
_sharedService = sharedService;
}
}
public interface ISharedService {
string AdapterName { get; set; }
}
public class SharedService : BindableBase, ISharedService {
private string _adapterName;
public string AdapterName {
get { return _adapterName; }
set { SetValue (ref _adapterName, value); }
}
}
我同時具有ViewA和ViewB的文本框,並且我希望ViewA中的文本框中的值始終與ViewB中的相同。 所以我應該更改AdapterNameA中的SharedService.AdapterName值來獲取,設置(類似於AdapterNameB)嗎?
public string AdapterNameA
{
get {
_adapterNameA = SharedService.AdapterName;
return _adapterNameA;
}
set {
SetValue (ref _adapterNameA, value);
SharedService.AdapterName = value;
}
}
或直接綁定到SharedService屬性
Text = "{Binding Path=SharedService.AdapterName, UpdateSourceTrigger=PropertyChanged}"
還是另一種方式? (我正在嘗試使用Prism制作WPF MVVM)
如果共享服務實現INotifyPropertyChanged
事件並引發更改通知,則您可以直接綁定到其屬性,前提是您確實希望通過視圖模型的屬性公開該服務。 您可能不想根據服務的功能執行此操作。
如果您不想公開該服務,則可以在視圖模型中創建包裝器屬性。 這樣可以提供更好的封裝,但會浪費一些包裝屬性的代碼行(如果有的話)。
但是,這里沒有真正的對與錯。 您將必須確定在這種特定情況下哪種解決方案最適合您。
通常,服務應該抽象化並負責從某處獲取一些結果,並將其傳遞回視圖模型。 它通常不實現INotifyPropertyChanged
事件,也不公開視圖直接綁定到的屬性。 視圖模型負責定義和公開此屬性。 視圖模型仍可以使用服務來填充屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.