Reputation: 7336
I need to update the Language
property in MyVM1
and MyVM2
when the Language
property changes in LanguageVM
(see image).
Upvotes: 1
Views: 551
Reputation: 3274
I personally prefer interface based programming and readability of dependencies. See below
Code is not compiled or tested and only given to convey the idea.
Your viewmodels are "language aware". Create an interface for this functionality
public interface ILanguageAware
{
void ChangeLanguage(string lang);
}
implement the interface
public class MyVM1:ILanguageAware
{
public void ChangeLanguage(string lang)
{
//do the language change tasks
}
}
Your provider can have the capability to keep the language aware objects
public interface ILanguageProvider
{
void AddLanguageAwareObject(ILanguageAware langawareobj) ;
void RemoveLanguageAwareObject(ILanguageAware langawareobj) ;
}
Your viewmodels can add themselves the language provider
public MyVM1:ILanguageAware
{
ILanguageProvider _langprovider =null;
public MyVM1(ILanguageProvider provider)
{
_langprovider = provider;
_langprovider.AddLanguageAwareObject(this);
}
}
Implement the provider
public class LanguageProvider:ILanguageProvider
{
List<ILanguageAware> _langawarelist = new List<ILanguageAware>();
void AddLanguageAwareObject(ILanguageAware langawareobj)
{
_langawarelist .Add(langawareobj);
}
public void SetLanguage(string lang)
{
_langawarelist .foreach(x=>x.ChangeLanguage(lang);
}
}
Upvotes: 1
Reputation: 5935
You have a lot of approaches to accomplish this. You can define an event in your LanguageProvider class. If you can have only one LanguageProvider object, you can mark the event as static, so you do not need to pass reference to LanguageProvider to YoursVM classes.
public static class LanguageProvider
{
private Language currentLanguage = Language.DefaultLanguage;
public delegate void LanguageChangedEventHandler(object sender, LanguageChangedEventArgs e);
public static event LanguageChangedEventHandler LanguageChanged;
public static void SetLanguage(string langId)
{
var oldLang = currentLanguage;
currentLanguage = new Language(langId);
if (LanguageChangedEventHandler != null)
{
LanguageChangedEventHandler(null, new LanguageChangedEventArgs(oldLangId:oldLang, newLang:currentLanguage));
}
}
}
And in your BaseVM base constructor:
public BaseVM()
{
...
LanguageProvider.LanguageChanged += OnLanguageChanged;
...
}
private void OnLanguageChanged(object sender, LanguageChangedEventArgs e)
{
this.Language = e.NewValue;
}
Upvotes: 0