当其他viewmodel中的内容发生更改时,WPF MVVM在viewmodel中更新属性

时间:2014-03-08 11:20:18

标签: wpf mvvm

Language MyVM1属性在MyVM2中更改时,我需要更新LanguageLanguageVM中的{{1}}属性。(参见图片)。

enter image description here

2 个答案:

答案 0 :(得分:1)

我个人更喜欢基于接口的编程和依赖项的可读性。见下文

代码未编译或测试,仅用于传达该想法。

您的视图模型是“语言识别”。为此功能创建一个界面

public interface ILanguageAware
{
   void ChangeLanguage(string lang);
}

实现界面

public class MyVM1:ILanguageAware
{
  public void ChangeLanguage(string lang)
  {
    //do the language change tasks
  }
}

您的提供商可以保留语言识别对象

public interface ILanguageProvider
{
   void AddLanguageAwareObject(ILanguageAware langawareobj) ;

   void RemoveLanguageAwareObject(ILanguageAware langawareobj) ;
} 

您的viewmodels可以自己添加语言提供程序

public MyVM1:ILanguageAware
{
  ILanguageProvider _langprovider =null;

  public MyVM1(ILanguageProvider provider)
  {
    _langprovider = provider;
    _langprovider.AddLanguageAwareObject(this);
  }

}

实施提供者

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);

  }    

}

答案 1 :(得分:0)

你有很多方法可以做到这一点。您可以在 LanguageProvider 类中定义 event 。如果您只能拥有一个 LanguageProvider 对象,则可以将该事件标记为静态,因此您无需将对 LanguageProvider 的引用传递给< strong> YoursVM 类。

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)); 
        }
    }         
}

BaseVM 基础构造函数中:

public BaseVM()
{
    ...
    LanguageProvider.LanguageChanged += OnLanguageChanged;
    ...
}

private void OnLanguageChanged(object sender, LanguageChangedEventArgs e)
{
    this.Language = e.NewValue;
}