Exemplo n.º 1
0
            void Init()
            {
                object vm = null;

                if (Factory != null)
                {
                    vm = Factory();
                }
                else if (ViewModelName != null)
                {
                    vm = viewModelLocator.ResolveViewModel(ViewModelName);
                }
                if (vm == null)
                {
                    ModuleInjectionException.NullVM();
                }
                viewModelRef = new WeakReference(vm);
                InitParameter();
                if (string.IsNullOrEmpty(ViewModelName))
                {
                    ViewModelName = viewModelLocator.GetViewModelTypeName(vm.GetType());
                }
                InitViewType();
                InitViewName();
            }
#pragma warning disable AvoidAsyncVoid
        async partial void NavigateWithParameters(string uri, Dictionary <string, object> parameters)
#pragma warning restore AvoidAsyncVoid
        {
            var viewType      = Type.GetType(uri);
            var viewModelType = _viewModelLocator.ResolveViewModel(viewType);
            var view          = (Page)_typeFactory.CreateInstance(viewType);
            var viewModel     = _viewModelFactory.CreateViewModel(viewModelType, parameters.Count > 0 ? parameters.Values.ToArray() : null);

            view.BindingContext = viewModel;

            var currentApplication = Application.Current;
            var activePage         = currentApplication.GetActivePage();

            if (activePage is null)
            {
                return;
            }

            var navigation = activePage.Navigation;

            if (navigation is null)
            {
                return;
            }

            await navigation.PushAsync(view);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="UIViewController"/> class.
        /// </summary>
        public UIViewController()
        {
            if (CatelEnvironment.IsInDesignMode)
            {
                return;
            }

            var viewModelType = GetViewModelType();

            if (viewModelType is null)
            {
                Log.Debug("GetViewModelType() returned null, using the ViewModelLocator to resolve the view model");

                viewModelType = _viewModelLocator.ResolveViewModel(GetType());
                if (viewModelType is null)
                {
                    const string error = "The view model of the view could not be resolved. Use either the GetViewModelType() method or IViewModelLocator";
                    Log.Error(error);
                    throw new NotSupportedException(error);
                }
            }

            _logic = new PageLogic(this, viewModelType);
            _logic.TargetViewPropertyChanged += (sender, e) =>
            {
                OnPropertyChanged(e);

                PropertyChanged?.Invoke(this, e);
            };

            _logic.ViewModelChanged += (sender, e) => RaiseViewModelChanged();

            _logic.ViewModelPropertyChanged += (sender, e) =>
            {
                OnViewModelPropertyChanged(e);

                ViewModelPropertyChanged?.Invoke(this, e);
            };

            _logic.DetermineViewModelInstance += (sender, e) =>
            {
                e.ViewModel = GetViewModelInstance(e.DataContext);
            };

            _logic.DetermineViewModelType += (sender, e) =>
            {
                e.ViewModelType = GetViewModelType(e.DataContext);
            };

            _logic.ViewLoading   += (sender, e) => ViewLoading?.Invoke(this);
            _logic.ViewLoaded    += (sender, e) => ViewLoaded?.Invoke(this);
            _logic.ViewUnloading += (sender, e) => ViewUnloading?.Invoke(this);
            _logic.ViewUnloaded  += (sender, e) => ViewUnloaded?.Invoke(this);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="LogicBase"/> class.
        /// </summary>
        /// <param name="targetView">The target control.</param>
        /// <param name="viewModelType">Type of the view model.</param>
        /// <param name="viewModel">The view model.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="targetView"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="viewModelType"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="viewModelType"/> does not implement interface <see cref="IViewModel"/>.</exception>
        protected LogicBase(IView targetView, Type viewModelType = null, IViewModel viewModel = null)
        {
            if (CatelEnvironment.IsInDesignMode)
            {
                return;
            }

            Argument.IsNotNull("targetView", targetView);

            var targetViewType = targetView.GetType();

            if (viewModelType is null)
            {
                viewModelType = (viewModel != null) ? viewModel.GetType() : _viewModelLocator.ResolveViewModel(targetViewType);
                if (viewModelType is null)
                {
                    throw Log.ErrorAndCreateException <NotSupportedException>($"The view model of the view '{targetViewType.Name}' could not be resolved. Make sure to customize the IViewModelLocator or register the view and view model manually");
                }
            }

            UniqueIdentifier = UniqueIdentifierHelper.GetUniqueIdentifier <LogicBase>();

            Log.Debug($"Constructing behavior '{GetType().Name}' for '{targetView.GetType().Name}' with unique id '{UniqueIdentifier}'");

            TargetView    = targetView;
            ViewModelType = viewModelType;
            ViewModel     = viewModel;

            ViewModelBehavior = (viewModel != null) ? LogicViewModelBehavior.Injected : LogicViewModelBehavior.Dynamic;

            if (ViewModel != null)
            {
                SetDataContext(ViewModel);
            }

            Log.Debug("Subscribing to view events");

            ViewLoadManager.AddView(this);

            if (this.SubscribeToWeakGenericEvent <ViewLoadEventArgs>(ViewLoadManager, nameof(IViewLoadManager.ViewLoading), OnViewLoadedManagerLoadingInternal, false) is null)
            {
                Log.Debug("Failed to use weak events to subscribe to 'ViewLoadManager.ViewLoading', going to subscribe without weak events");

                ViewLoadManager.ViewLoading += OnViewLoadedManagerLoadingInternal;
            }

            if (this.SubscribeToWeakGenericEvent <ViewLoadEventArgs>(ViewLoadManager, nameof(IViewLoadManager.ViewLoaded), OnViewLoadedManagerLoadedInternal, false) is null)
            {
                Log.Debug("Failed to use weak events to subscribe to 'ViewLoadManager.ViewLoaded', going to subscribe without weak events");

                ViewLoadManager.ViewLoaded += OnViewLoadedManagerLoadedInternal;
            }

            if (this.SubscribeToWeakGenericEvent <ViewLoadEventArgs>(ViewLoadManager, nameof(IViewLoadManager.ViewUnloading), OnViewLoadedManagerUnloadingInternal, false) is null)
            {
                Log.Debug("Failed to use weak events to subscribe to 'ViewLoadManager.ViewUnloading', going to subscribe without weak events");

                ViewLoadManager.ViewUnloading += OnViewLoadedManagerUnloadingInternal;
            }

            if (this.SubscribeToWeakGenericEvent <ViewLoadEventArgs>(ViewLoadManager, nameof(IViewLoadManager.ViewUnloaded), OnViewLoadedManagerUnloadedInternal, false) is null)
            {
                Log.Debug("Failed to use weak events to subscribe to 'ViewLoadManager.ViewUnloaded', going to subscribe without weak events");

                ViewLoadManager.ViewUnloaded += OnViewLoadedManagerUnloadedInternal;
            }

            // Required so the ViewLoadManager can handle the rest
            targetView.Loaded   += (sender, e) => Loaded?.Invoke(this, EventArgs.Empty);
            targetView.Unloaded += (sender, e) => Unloaded?.Invoke(this, EventArgs.Empty);

            TargetView.DataContextChanged += OnTargetViewDataContextChanged;

            Log.Debug("Subscribing to view properties");

            // This also subscribes to DataContextChanged, don't double subscribe
            var viewPropertiesToSubscribe = DetermineInterestingViewProperties();

            foreach (var viewPropertyToSubscribe in viewPropertiesToSubscribe)
            {
                TargetView.SubscribeToPropertyChanged(viewPropertyToSubscribe, OnTargetViewPropertyChanged);
            }

            Log.Debug($"Constructed behavior '{GetType().Name}' for '{TargetViewType?.Name}'");
        }
Exemplo n.º 5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Page"/> class.
        /// </summary>
        /// <remarks>
        /// It is not possible to inject view models.
        /// </remarks>
        public Page()
        {
            if (Catel.Environment.IsInDesignMode)
            {
                return;
            }

            var viewModelType = GetViewModelType();

            if (viewModelType == null)
            {
                Log.Debug("GetViewModelType() returned null, using the ViewModelLocator to resolve the view model");

                viewModelType = _viewModelLocator.ResolveViewModel(GetType());
                if (viewModelType == null)
                {
                    const string error = "The view model of the view could not be resolved. Use either the GetViewModelType() method or IViewModelLocator";
                    Log.Error(error);
                    throw new NotSupportedException(error);
                }
            }

            _logic = new NavigationPageLogic(this, viewModelType);
            _logic.TargetControlPropertyChanged += (sender, e) =>
            {
#if !NET
                // WPF already calls this method automatically
                OnPropertyChanged(e.FxEventArgs);

                // Do not call this for WPF, will cause problems with ActualWidth and ActualHeight
                PropertyChanged.SafeInvoke(this, new PropertyChangedEventArgs(e.PropertyName));
#endif
            };

            _logic.ViewModelChanged += (sender, e) =>
            {
                OnViewModelChanged();

                ViewModelChanged.SafeInvoke(this, e);
                PropertyChanged.SafeInvoke(this, new PropertyChangedEventArgs("ViewModel"));
            };

            _logic.ViewModelPropertyChanged += (sender, e) =>
            {
                OnViewModelPropertyChanged(e);

                ViewModelPropertyChanged.SafeInvoke(this, e);
            };

            _logic.DetermineViewModelInstance += (sender, e) =>
            {
                e.ViewModel = GetViewModelInstance(e.DataContext);
            };

            _logic.DetermineViewModelType += (sender, e) =>
            {
                e.ViewModelType = GetViewModelType(e.DataContext);
            };

            ViewModelChanged.SafeInvoke(this);

            Loaded   += (sender, e) => OnLoaded(e);
            Unloaded += (sender, e) => OnUnloaded(e);
        }
Exemplo n.º 6
0
 public static T ResolveViewModel <T>(this IViewModelLocator vml) => (T)vml?.ResolveViewModel(typeof(T).Name);
Exemplo n.º 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PhoneApplicationPage"/> class.
        /// </summary>
        /// <remarks>
        /// It is not possible to inject view models (actually, you can't even
        /// pass view models during navigation in Windows Phone 7).
        /// </remarks>
        public PhoneApplicationPage()
        {
            if (Catel.Environment.IsInDesignMode)
            {
                return;
            }

            var viewModelType = GetViewModelType();

            if (viewModelType == null)
            {
                Log.Debug("GetViewModelType() returned null, using the ViewModelLocator to resolve the view model");

                viewModelType = _viewModelLocator.ResolveViewModel(GetType());
                if (viewModelType == null)
                {
                    const string error = "The view model of the view could not be resolved. Use either the GetViewModelType() method or IViewModelLocator";
                    Log.Error(error);
                    throw new NotSupportedException(error);
                }
            }

            _logic = new PhoneApplicationPageLogic(this, viewModelType);
            _logic.TargetControlPropertyChanged += (sender, e) =>
            {
                OnPropertyChanged(e.FxEventArgs);

                PropertyChanged.SafeInvoke(this, new PropertyChangedEventArgs(e.PropertyName));
            };

            _logic.ViewModelChanged += (sender, e) =>
            {
                OnViewModelChanged();

                ViewModelChanged.SafeInvoke(this, e);
                PropertyChanged.SafeInvoke(this, new PropertyChangedEventArgs("ViewModel"));
            };

            _logic.ViewModelPropertyChanged += (sender, e) =>
            {
                OnViewModelPropertyChanged(e);

                ViewModelPropertyChanged.SafeInvoke(this, e);
            };

            _logic.DetermineViewModelInstance += (sender, e) =>
            {
                e.ViewModel = GetViewModelInstance(e.DataContext);
            };

            _logic.DetermineViewModelType += (sender, e) =>
            {
                e.ViewModelType = GetViewModelType(e.DataContext);
            };

            _logic.ViewLoading   += (sender, e) => ViewLoading.SafeInvoke(this);
            _logic.ViewLoaded    += (sender, e) => ViewLoaded.SafeInvoke(this);
            _logic.ViewUnloading += (sender, e) => ViewUnloading.SafeInvoke(this);
            _logic.ViewUnloaded  += (sender, e) => ViewUnloaded.SafeInvoke(this);

            _logic.Tombstoning += (sender, e) => OnTombstoning();
            _logic.Tombstoned  += (sender, e) => OnTombstoned();
            _logic.RecoveringFromTombstoning += (sender, e) => OnRecoveringFromTombstoning();
            _logic.RecoveredFromTombstoning  += (sender, e) => OnRecoveredFromTombstoning();

            ViewModelChanged.SafeInvoke(this);

            Loaded   += (sender, e) => OnLoaded(e);
            Unloaded += (sender, e) => OnUnloaded(e);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="UserControl"/> class.
        /// </summary>
        /// <param name="viewModel">The view model.</param>
        public UserControl(IViewModel viewModel)
        {
            if (Catel.Environment.IsInDesignMode)
            {
                return;
            }

            var viewModelType = (viewModel != null) ? viewModel.GetType() : GetViewModelType();

            if (viewModelType == null)
            {
                Log.Debug("GetViewModelType() returned null, using the ViewModelLocator to resolve the view model");

                viewModelType = ViewModelLocator.ResolveViewModel(GetType());
                if (viewModelType == null)
                {
                    const string error = "The view model of the view could not be resolved. Use either the GetViewModelType() method or IViewModelLocator";
                    Log.Error(error);
                    throw new NotSupportedException(error);
                }
            }

            _logic = new UserControlLogic(this, viewModelType, viewModel);
            _logic.TargetControlPropertyChanged += (sender, e) =>
            {
#if !NET
                // WPF already calls this method automatically
                OnPropertyChanged(e.FxEventArgs);

                PropertyChanged.SafeInvoke(this, new PropertyChangedEventArgs(e.PropertyName));
#else
                // Do not call this for ActualWidth and ActualHeight WPF, will cause problems with NET 40
                // on systems where NET45 is *not* installed
                if (!string.Equals(e.PropertyName, "ActualWidth", StringComparison.InvariantCulture) &&
                    !string.Equals(e.PropertyName, "ActualHeight", StringComparison.InvariantCulture))
                {
                    PropertyChanged.SafeInvoke(this, new PropertyChangedEventArgs(e.PropertyName));
                }
#endif
            };

            _logic.ViewModelChanged += (sender, e) =>
            {
                OnViewModelChanged();

                ViewModelChanged.SafeInvoke(this, e);
                PropertyChanged.SafeInvoke(this, new PropertyChangedEventArgs("ViewModel"));
            };

            _logic.ViewModelPropertyChanged += (sender, e) =>
            {
                OnViewModelPropertyChanged(e);

                ViewModelPropertyChanged.SafeInvoke(this, e);
            };

            _logic.DetermineViewModelInstance += (sender, e) =>
            {
                e.ViewModel = GetViewModelInstance(e.DataContext);
            };

            _logic.DetermineViewModelType += (sender, e) =>
            {
                e.ViewModelType = GetViewModelType(e.DataContext);
            };

            _logic.ViewLoading   += (sender, e) => ViewLoading.SafeInvoke(this);
            _logic.ViewLoaded    += (sender, e) => ViewLoaded.SafeInvoke(this);
            _logic.ViewUnloading += (sender, e) => ViewUnloading.SafeInvoke(this);
            _logic.ViewUnloaded  += (sender, e) => ViewUnloaded.SafeInvoke(this);

            _logic.ViewModelClosed += OnViewModelClosed;

            Loaded   += (sender, e) => OnLoaded(e);
            Unloaded += (sender, e) => OnUnloaded(e);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="LogicBase"/> class.
        /// </summary>
        /// <param name="targetView">The target control.</param>
        /// <param name="viewModelType">Type of the view model.</param>
        /// <param name="viewModel">The view model.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="targetView"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="viewModelType"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="viewModelType"/> does not implement interface <see cref="IViewModel"/>.</exception>
        protected LogicBase(IView targetView, Type viewModelType = null, IViewModel viewModel = null)
        {
            Argument.IsNotNull("targetView", targetView);

            if (viewModelType == null)
            {
                viewModelType = (viewModel != null) ? viewModel.GetType() : _viewModelLocator.ResolveViewModel(targetView.GetType());
                if (viewModelType == null)
                {
                    var error = string.Format("The view model of the view '{0}' could not be resolved. Make sure to customize the IViewModelLocator or register the view and view model manually", targetView.GetType().GetSafeFullName());
                    Log.Error(error);
                    throw new NotSupportedException(error);
                }
            }

            UniqueIdentifier = UniqueIdentifierHelper.GetUniqueIdentifier <LogicBase>();

            Log.Debug("Constructing behavior '{0}' for '{1}' with unique id '{2}'", GetType().Name, targetView.GetType().Name, UniqueIdentifier);

            TargetView    = targetView;
            ViewModelType = viewModelType;
            ViewModel     = viewModel;

#if SL5
            Catel.Windows.FrameworkElementExtensions.FixUILanguageBug((System.Windows.FrameworkElement)TargetView);
#endif

            ViewModelBehavior = (viewModel != null) ? LogicViewModelBehavior.Injected : LogicViewModelBehavior.Dynamic;

            if (ViewModel != null)
            {
                SetDataContext(ViewModel);
            }

            // Very impoortant to exit here in design mode
            if (CatelEnvironment.IsInDesignMode)
            {
                return;
            }

            Log.Debug("Subscribing to view events");

            ViewLoadManager.AddView(this);
            this.SubscribeToWeakGenericEvent <ViewLoadEventArgs>(ViewLoadManager, "ViewLoading", OnViewLoadedManagerLoading);
            this.SubscribeToWeakGenericEvent <ViewLoadEventArgs>(ViewLoadManager, "ViewLoaded", OnViewLoadedManagerLoaded);
            this.SubscribeToWeakGenericEvent <ViewLoadEventArgs>(ViewLoadManager, "ViewUnloading", OnViewLoadedManagerUnloading);
            this.SubscribeToWeakGenericEvent <ViewLoadEventArgs>(ViewLoadManager, "ViewUnloaded", OnViewLoadedManagerUnloaded);

            // Required so the ViewLoadManager can handle the rest
            targetView.Loaded   += (sender, e) => Loaded.SafeInvoke(this);
            targetView.Unloaded += (sender, e) => Unloaded.SafeInvoke(this);

            TargetView.DataContextChanged += OnTargetViewDataContextChanged;

            Log.Debug("Subscribing to view properties");

            // This also subscribes to DataContextChanged, don't double subscribe
            var viewPropertiesToSubscribe = DetermineInterestingViewProperties();
            foreach (var viewPropertyToSubscribe in viewPropertiesToSubscribe)
            {
                TargetView.SubscribeToPropertyChanged(viewPropertyToSubscribe, OnTargetViewPropertyChanged);
            }

            Log.Debug("Constructed behavior '{0}' for '{1}'", GetType().Name, TargetView.GetType().Name);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Resolves a view model type by the view and the registered <see cref="ILocator.NamingConventions" />.
        /// </summary>
        /// <typeparam name="TView">The type of the view.</typeparam>
        /// <param name="viewModelLocator">The view model locator.</param>
        /// <returns>The resolved view model or <c>null</c> if the view model could not be resolved.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="viewModelLocator" /> is <c>null</c>.</exception>
        /// <remarks>Keep in mind that all results are cached. The cache itself is not automatically cleared when the
        /// <see cref="ILocator.NamingConventions" /> are changed. If the <see cref="ILocator.NamingConventions" /> are changed,
        /// the cache must be cleared manually.</remarks>
        public static Type ResolveViewModel <TView>(this IViewModelLocator viewModelLocator)
        {
            Argument.IsNotNull("viewModelLocator", viewModelLocator);

            return(viewModelLocator.ResolveViewModel(typeof(TView)));
        }