• MVVM之View和ViewModel的关联


    概要:

    将所有的VM在加载到Application的Static Resource中,然后在View中用标签指定。

    实现:

    1)采用特性指定要添加到StaticResource中的对象

    publicclassStaticResourceAttribute : Attribute
        {
            publicstringKey { get; set; }
      
            publicStaticResourceAttribute(stringkey)
            {
                this.Key = key;
            }
        }

    2)从当前的程序集中,把所有标记了StaticResourceAttribute的VM加载到AppResource中

    publicclassViewModelManager
        {
            privatestaticApplication app = Application.Current;
      
            publicstaticvoidInjectViewModelsToResources()
            {
                Assembly executingAssembly = Assembly.GetCallingAssembly();
                foreach(Type type inexecutingAssembly.GetTypes())
                {
                    var attributes = type.GetCustomAttributes(false);
      
                    foreach(var attribute inattributes)
                    {
                        if(attribute isStaticResourceAttribute)
                        {
                            var obj = Activator.CreateInstance(type);
                            if(!app.Resources.Contains(type.Name))
                                app.Resources.Add(type.Name, obj);
                        }
                    }
                }
            }
      
            publicstaticT GetViewModelFromResources<T>()
            {
                var key = typeof(T).Name;
                if(app.Resources.Contains(key))
                    return(T)app.Resources[key];
                else
                    returndefault(T);
            }
        }

    在主窗体中调用:

    publicpartialclassMainPage : UserControl
        {
            publicMainPage()
            {
                ViewModelManager.InjectViewModelsToResources();
                  
                InitializeComponent();         
            }
        }

    3)View写法

    <UserControlx:Class="XXX .LoginView"
     <UserControl.DataContext>
            <BindingSource="{StaticResource LoginViewModel}"/>
        </UserControl.DataContext>
      
      
    </UserControl>

    结论:

    这样处理后,实现了VM的"单例",多个View关联同一个VM时可以共享数据。

  • 相关阅读:
    pyecharts包学习笔记
    敏捷测试关键成功因素
    JMeter—常见问题(十四)
    性能测试面试题
    python-Tkinter整理总结
    JMeter—系统性能分析思路(十三)
    JMeter—监听器(十二)
    JMeter—断言(十一)
    yii2.0 的数据的 增
    Windows下安装 使用coreseek
  • 原文地址:https://www.cnblogs.com/luluping/p/2077218.html
Copyright © 2020-2023  润新知