Is there a way to bind property of the VM to any kind of singleton property ( static resource property, property in the singleton service... ) in a way that we don't need to use IMessenger or to handle SingletonServiceResolved OnPropertyChanged?
It feels kind of dirty for me (even if it is in the base class) to have each activity to handle changes in my singleton Clock Property.
public class ClockService : ObservableObject, IClockService {
private DateTime _clock;
public DateTime Clock {
get{ return _clock;}
set { _clock = value; RaisePropertyChanged("Clock"); }
}
}
public class SomeViewModel : BaseViewModel {
private IClockService _clockService;
private IMvxMessenger _messenger;
public SomeViewModel(IClockService clockService, IMvxMessenger messenger) {
_clockService=clockService;
_messenger = messenger;
//trying to avoid
clockService.PropertyChanged += OnClockServicePropertyChanged;
}
public DateTime MyClock {
get{return _clockService.Clock;}
}
private OnClockServicePropertyChanged(...) {
if(e.PropertyName=="Clock") RaisePropertyChanged("Clock");
}
}
One way to bind to a singleton is to expose the singleton via a property on your ViewModel:
public Thing MySingleton
{
get
{
return Thing.Instance;
}
}
Update after comment that the singleton isn't constant:
You could use another constant singleton as a holder - and this can then implement INotifyPropertyChanged
- e.g.:
public class ThingHolder : MvxNotifyPropertyChanged
{
public static readonly ThingHolder Instance = new ThingHolder();
private Thing _thing;
public Thing CurrentThing
{
get { return _thing; }
set { _thing = value; RaisePropertyChanged(() => CurrentThing); }
}
}
Your VMs can then properties like:
public ThingHolder ThingHolder
{
get
{
return ThingHolder.Instance;
}
}
Your views can then bind to expressions like ThingHolder.CurrentThing