VMs in different assembly

Aug 24, 2010 at 2:23 PM

Hi,

Probably an easy question... is there any guideline for the case when you have the view model in a different assembly than the view?

I don't want to use the "same" namespace for both in two different projects.

Thanks

 

Coordinator
Aug 24, 2010 at 2:53 PM

I normally replace the ViewLocator.LocateViewForModel method with a custom implementation. Just create a new function that knows how to do your namespace mapping.

Aug 27, 2010 at 7:53 AM

I ran into this problem yesterday, and solved it by modifying(just adding actually) the ViewLocator class' LocateForModelType Method like this:

        /// <summary>
        /// Locates the view for the specified model type.
        /// </summary>
        /// <returns>The view.</returns>
        /// <remarks>Pass the model type, display location (or null) and the context instance (or null) as parameters and recieve a view instance.</remarks>
        public static Func<Type, DependencyObject, object, UIElement> LocateForModelType = (modelType, displayLocation, context) =>
        {
            var viewTypeName = modelType.FullName.Replace("Model", string.Empty);
            if (context != null)
            {
                viewTypeName = viewTypeName.Remove(viewTypeName.Length - 4, 4);
                viewTypeName = viewTypeName + "." + context;
            }

            var viewType = (from assmebly in AssemblySource.Instance
                            from type in assmebly.GetExportedTypes()
                            where type.FullName == viewTypeName
                            select type).FirstOrDefault();

            if (viewType == null)
            {
                viewType = (from assmebly in AssemblySource.Instance
                            from type in assmebly.GetExportedTypes()
                            where type.FullName == type.FullName.Substring(0, type.FullName.LastIndexOf('.')) + viewTypeName.Substring(viewTypeName.LastIndexOf('.'))
                            select type).FirstOrDefault();
            }

            return viewType == null
                ? new TextBlock { Text = string.Format("{0} not found.", viewTypeName) }
                : GetOrCreateViewType(viewType);
        };