建立可扩展的silverlight 应用框架 step-5

2018-01-16 11:42:59 浏览数 (1)

整理Module

在第三节里边,建立了一个最简单的Module。这里要对其再进行整理。之前我写过一篇《简练的视图模型 ViewModel》这里就讲述了一个最最基本的运用视图与模型的例子。用模型来控制视图的呈现在很早的时候就提出来了。当然Prism这个框架也包括了这一点。这里就要为Module加入Model。 这里记录下整理步骤

1.在Module项目中新建立一个Models文件夹,用来存放数据模型。在文件下新建立一个HelloPrismModel类继承自INotifyPropertyChanged。

在构造函数中将视图作为参数传入将视图和模型相绑定。

代码语言:javascript复制
    public class HelloPrismModel : INotifyPropertyChanged
    {
        public HelloPrismView view { get; private set; }

        public HelloPrismModel(HelloPrismView view)
        {
            this.view = view;
            view.model = this;
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;


        private void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion

    }

2.在Views文件下新建立一个IHelloPrismView接口。

在接口中声明其模型属性

代码语言:javascript复制
    public interface IHelloPrismView
    {
        HelloPrismModel model { get; set; }
    }

3.修改原来的HelloPrismView.xaml继承自IHelloPrismView接口并且实现接口。

代码语言:javascript复制
    public partial class HelloPrismView : UserControl, IHelloPrismView
    {
        private readonly IModuleManager moduleManager;

        public HelloPrismView()
        {
            InitializeComponent();
        }
        public HelloPrismView(IModuleManager moduleManager):this()
        {
            this.moduleManager = moduleManager;
        }
        #region IHelloPrismView Members

        public HelloPrismModel model
        {
            get { return this.DataContext as HelloPrismModel; }
            set { this.DataContext = value; }
        }

        #endregion
    }

4.最后重构一下HelloPrismModule类

代码语言:javascript复制
    public class HelloPrismModule : IModule
    {
        private readonly IRegionManager regionManager;
        private readonly IUnityContainer container;
        private readonly IModuleManager moduleManager;

        public HelloPrismModule(IUnityContainer container, IRegionManager regionManager, IModuleManager moduleManager)
        {
            this.container = container;
            this.regionManager = regionManager;
            this.moduleManager = moduleManager;
        }

        public void Initialize()
        {
            HelloPrismModel helloPrismModel = this.container.Resolve<HelloPrismModel>();

            IRegion mainRegion = this.regionManager.Regions["MainRegion"];

            object view = mainRegion.GetView("mainCurrView");
            if (view != null)
                mainRegion.Remove(view);

            mainRegion.Add(helloPrismModel.view, "mainCurrView");
        }

    }  

0 人点赞