コード例 #1
0
        /// <summary>
        /// Creates and Binds a viewmodel to a view
        /// </summary>
        /// <param name="injectionScope"></param>
        /// <param name="view">view to bind to</param>
        /// <param name="viewModelName">name of the view model to bind to</param>
        public bool ResolveViewModel(IExportLocator injectionScope, FrameworkElement view, string viewModelName)
        {
            bool foundModel = false;
            object viewModel = null;
            object oldViewModel = view.DataContext;

            if (!string.IsNullOrEmpty(viewModelName))
            {
                try
                {
                    IInjectionContext injectionContext = injectionScope.CreateContext();
                    IViewContext viewContext = new ViewContext(view);

                    injectionContext.Export((s, c) => viewContext);

                    viewModel = injectionScope.Locate(viewModelName, injectionContext);

                    if (viewModel != null)
                    {
                        foundModel = true;

                        Logger.Debug(string.Format("Resolved ViewModel Name {0} to Type {1}", viewModelName, viewModel.GetType().FullName));
                    }
                }
                catch (Exception exp)
                {
                    Logger.Error("Exception thrown while creating ViewModel: " + viewModelName, SUPPLEMENTAL_STRING, exp);
                }
            }

            if (foundModel)
            {
                ProcessNewModel(view, viewModel);

                ProcessOldModel(view, oldViewModel);
            }

            return foundModel;
        }