示例#1
0
        static UIElement LocateForModelType(Type modelType, DependencyObject viewLocation, object context,
                                            Func <Type, DependencyObject, object, UIElement> original)
        {
            string viewTypeName;

            if (modelType.Assembly != Assembly.GetExecutingAssembly())
            {
                var name = "Raven.Studio.Data." + modelType.Name;

                if (name.Contains("`"))
                {
                    name = name.Substring(0, name.IndexOf("`"));
                }

                viewTypeName = name + "View";

                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)
                {
                    return(ViewLocator.GetOrCreateViewType(viewType));
                }
            }
            return(original(modelType, viewLocation, context));
        }
示例#2
0
        public static UIElement LocateForModelType(
            Type modelType,
            DependencyObject viewLocation,
            object context,
            Func <Type, DependencyObject, object, UIElement> original)
        {
            // case 1: types that are not in the Studio assembly
            if (modelType.Assembly != Assembly.GetExecutingAssembly())
            {
                UIElement view;
                if (TryResolveViewFromExternalAssembly(modelType, context, out view))
                {
                    return(view);
                }
            }

            // case 2: simplified convention
            string viewTypeName = modelType.FullName + "View";
            Type   viewType     = (from assmebly in AssemblySource.Instance
                                   from type in assmebly.GetExportedTypes()
                                   where type.FullName == viewTypeName
                                   select type).FirstOrDefault();

            if (viewType != null)
            {
                return(ViewLocator.GetOrCreateViewType(viewType));
            }

            // case 3: apply the default when all else fails
            return(original(modelType, viewLocation, context));
        }
示例#3
0
        static bool TryResolveViewFromPluginAssembly(Type modelType, object context, out UIElement view)
        {
            view = null;
            var viewType = GetViewType(modelType, context, modelType.Assembly);

            if (viewType != null)
            {
                view = ViewLocator.GetOrCreateViewType(viewType);
                return(true);
            }
            return(false);
        }
示例#4
0
        private void InitializeViewLocator(IBootstrapper bootstrapper)
        {
            //overriden for performance reasons (Assembly caching)
            ViewLocator.LocateTypeForModelType = (modelType, displayLocation, context) =>
            {
                var viewTypeName = modelType.FullName.Substring(0, modelType.FullName.IndexOf("`") < 0
                    ? modelType.FullName.Length
                    : modelType.FullName.IndexOf("`")
                                                                ).Replace("Model", string.Empty);

                if (context != null)
                {
                    viewTypeName = viewTypeName.Remove(viewTypeName.Length - 4, 4);
                    viewTypeName = viewTypeName + "." + context;
                }

                Type viewType;
                if (!_typedic.TryGetValue(viewTypeName, out viewType))
                {
                    _typedic[viewTypeName] = viewType = (from assembly in bootstrapper.Assemblies
                                                         from type in assembly
#if NET || NETCORE
                                                         .GetExportedTypes()
#endif
#if WINDOWS_UWP || NETFX_CORE
                                                         .DefinedTypes
#endif
                                                         where type.FullName == viewTypeName
                                                         select type
#if WINDOWS_UWP || NETFX_CORE
                                                         .AsType()
#endif
                                                         ).FirstOrDefault();
                }

                return(viewType);
            };
            ViewLocator.LocateForModelType = (modelType, displayLocation, context) =>
            {
                var viewType = ViewLocator.LocateTypeForModelType(modelType, displayLocation, context);

                return(viewType == null
                    ? new TextBlock
                {
                    Text = $"Cannot find view for\nModel: {modelType}\nContext: {context} ."
                }
                    : ViewLocator.GetOrCreateViewType(viewType));
            };
        }
示例#5
0
        public static void Initialize()
        {
            Func <DependencyObject, string, TriggerBase> defaultCreateTrigger = Parser.CreateTrigger;

            Parser.CreateTrigger = (target, triggerText) =>
            {
                if (triggerText == null)
                {
                    return(defaultCreateTrigger(target, null));
                }

                string triggerDetail = triggerText
                                       .Replace("[", string.Empty)
                                       .Replace("]", string.Empty);

                string[] splits = triggerDetail.Split((char[])null, StringSplitOptions.RemoveEmptyEntries);

                switch (splits[0])
                {
                case "Key":
                    Key key = (Key)Enum.Parse(typeof(Key), splits[1], true);
                    return(new KeyTrigger {
                        Key = key
                    });

                case "Gesture":
                    MultiKeyGesture gesture = (MultiKeyGesture)(new MultiKeyGestureConverter()).ConvertFrom(splits[1]);
                    return(new KeyTrigger {
                        Modifiers = gesture.KeySequences[0].Modifiers, Key = gesture.KeySequences[0].Keys[0]
                    });
                }

                return(defaultCreateTrigger(target, triggerText));
            };

            Func <Type, DependencyObject, object, UIElement> defaultFunction = ViewLocator.LocateForModelType;

            ViewLocator.LocateForModelType = (type, o, arg) =>
            {
                if (typeof(ISettingsSectionViewModel).IsAssignableFrom(type))
                {
                    return(ViewLocator.GetOrCreateViewType(typeof(FormSettingSectionView)));
                }

                return(defaultFunction(type, o, arg));
            };
        }
示例#6
0
        private static void ConfigureViewLocator()
        {
            ViewLocator.LocateForModelType = (presenter, displayLocation, context) =>
            {
                if (presenter.Name.Contains("Proxy"))
                {
                    presenter = presenter.BaseType;
                }

                var viewType = context == null
            ? Assembly.GetExecutingAssembly().GetType(presenter.Namespace + ".View")
            : Assembly.GetExecutingAssembly().GetType(presenter.Namespace + "." + context.ToString());

                Asrt.True(viewType != null, String.Format("Could not find View for ViewModel: {0}.", presenter));

                return(ViewLocator.GetOrCreateViewType(viewType));
            };
        }
示例#7
0
        static bool TryResolveViewFromApi(Type modelType, object context, out UIElement view)
        {
            view = null;
            var name = "Raven.Studio.Data." + modelType.Name;

            if (name.Contains("`"))
            {
                name = name.Substring(0, name.IndexOf("`"));
            }

            var viewType = GetViewType(modelType, context, AssemblySource.Instance.ToArray());

            if (viewType != null)
            {
                view = ViewLocator.GetOrCreateViewType(viewType);
                return(true);
            }

            return(false);
        }
        public static void ConfigureViewLocator()
        {
            ViewLocator.LocateForModelType = (modelType, displayLocation, context) =>
            {
                var useViewAttributes = modelType.GetCustomAttributes(typeof(UseViewAttribute), true)
                                        .Cast <UseViewAttribute>();

                Contract.Assert(useViewAttributes.Count() <= 1, "There can only be zero or one UseViewAttribute on a view model");

                string viewTypeName;

                if (useViewAttributes.Count() == 1)
                {
                    viewTypeName = string.Concat(modelType.Namespace.Substring(0, modelType.Namespace.IndexOf(".ViewModels")), ".Views.",
                                                 useViewAttributes.First().ViewName);
                }
                else
                {
                    viewTypeName = modelType.FullName.Replace("Model", string.Empty);
                    if (context != null)
                    {
                        viewTypeName = viewTypeName.Remove(viewTypeName.Length - 4, 4);
                        viewTypeName = viewTypeName + "." + context;
                    }
                }

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

                return(viewType == null
                                        ? new TextBlock {
                    Text = string.Format("{0} not found.", viewTypeName)
                }
                                        : ViewLocator.GetOrCreateViewType(viewType));
            };
        }
示例#9
0
        public void Init(bool failfast)
        {
            MessageBus.Current.RegisterScheduler <string>(ImmediateScheduler.Instance, "db");

            ConventionManager.Singularize = s => {
                if (s == "Taxes")
                {
                    return("Tax");
                }
                if (s == "Value")
                {
                    return(s);
                }
                return(s.Singularize() ?? s);
            };
            //нужно затем что бы можно было делать модели без суффикса ViewModel
            //достаточно что бы они лежали в пространстве имен ViewModels
            ViewLocator.NameTransformer.AddRule(
                @"(?<nsbefore>([A-Za-z_]\w*\.)*)(?<subns>ViewModels\.)"
                + @"(?<nsafter>([A-Za-z_]\w*\.)*)(?<basename>[A-Za-z_]\w*)"
                + @"(?!<suffix>ViewModel)$",
                "${nsbefore}Views.${nsafter}${basename}View");
            //что бы не нужно было использовать суффиксы View и ViewModel
            ViewLocator.NameTransformer.AddRule(
                @"(?<nsbefore>([A-Za-z_]\w*\.)*)(?<subns>ViewModels\.)"
                + @"(?<nsafter>([A-Za-z_]\w*\.)*)(?<basename>[A-Za-z_]\w*)"
                + @"(?!<suffix>)$",
                "${nsbefore}Views.${nsafter}${basename}");

            //безумие - сам по себе Caliburn если не найден view покажет текст Cannot find view for
            //ни исключения ни ошибки в лог
            ViewLocator.LocateForModelType = (modelType, displayLocation, context) => {
                var viewType = ViewLocator.LocateTypeForModelType(modelType, displayLocation, context);
                if (viewType == null)
                {
                    if (failfast)
                    {
                        throw new Exception(String.Format("Не удалось найти вид для отображения {0}", modelType));
                    }
                    else
                    {
                        log.ErrorFormat("Не удалось найти вид для отображения {0}", modelType);
                    }
                }

                return(viewType == null
                                                        ? new TextBlock()
                                                        : ViewLocator.GetOrCreateViewType(viewType));
            };

            Conventions.Register();
            SaneCheckboxEditor.Register();
            NotifyValueSupport.Register();

            var customPropertyBinders = new Action <IEnumerable <FrameworkElement>, Type>[] {
                EnabledBinder.Bind,
                VisibilityBinder.Bind,
            };
            var customBinders = new Action <Type, IEnumerable <FrameworkElement>, List <FrameworkElement> >[] {
                //сначала должен обрабатываться поиск и только потом переход
                SearchBinder.Bind,
                NavBinder.Bind,
                EnterBinder.Bind,
            };

            var defaultBindProperties = ViewModelBinder.BindProperties;
            var defaultBindActions    = ViewModelBinder.BindActions;
            var defaultBind           = ViewModelBinder.Bind;

            ViewModelBinder.Bind = (viewModel, view, context) => {
                if ((bool)view.GetValue(ViewModelBinder.ConventionsAppliedProperty))
                {
                    return;
                }

                defaultBind(viewModel, view, context);
                ContentElementBinder.Bind(viewModel, view, context);
                Commands.Bind(viewModel, view, context);
                var baseScreen = viewModel as BaseScreen;
                //этот метод будет вызваться каждый раз при активации\деактивации формы
                //что бы избежать множественных подписок
                if (baseScreen != null && !baseScreen.ResultsSink.HasObservers)
                {
                    baseScreen.ResultsSink
                    .CatchSubscribe(r => Coroutine.BeginExecute(new List <IResult> {
                        r
                    }.GetEnumerator(), new ActionExecutionContext {
                        View = view
                    }), baseScreen.CloseCancellation);
                }
                var baseShell = viewModel as BaseShell;
                if (baseShell != null && !baseShell.ResultsSink.HasObservers)
                {
                    baseShell.ResultsSink
                    .CatchSubscribe(r => Coroutine.BeginExecute(new List <IResult> {
                        r
                    }.GetEnumerator(), new ActionExecutionContext {
                        View = view
                    }), baseShell.CancelDisposable);
                }
            };

            ViewModelBinder.BindProperties = (elements, type) => {
                foreach (var binder in customPropertyBinders)
                {
                    binder(elements, type);
                }
                return(defaultBindProperties(elements, type));
            };

            ViewModelBinder.BindActions = (elements, type) => {
                var binded = defaultBindActions(elements, type).ToList();

                foreach (var binder in customBinders)
                {
                    binder(type, elements, binded);
                }
                return(elements);
            };
        }