我使用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值get,set(与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)
答案 0 :(得分:0)
如果共享服务实现INotifyPropertyChanged
事件并引发更改通知,则可以直接绑定到其属性,前提是您确实希望通过视图模型的属性公开服务。您可能不希望这取决于服务的功能。
如果您不想公开该服务,您可以在视图模型中创建包装器属性。这提供了更好的封装,代价是包装器属性的一些额外代码行(如果你有几个)。
但这里没有真正的对错。在这种特定情况下,您必须决定哪种解决方案对您最有意义。
通常,服务应该抽象出来并负责从某处获取某些结果并将它们传递回视图模型。它通常不会实现INotifyPropertyChanged
事件并公开视图直接绑定到的属性。它是视图模型定义和公开此属性的责任。视图模型仍可以使用该服务来填充属性。