Example #1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ObjectObserver"/> class.
        /// </summary>
        /// <param name="propertyChanged">The property changed.</param>
        /// <param name="tag">The tag.</param>
        /// <param name="mementoService">The memento service. If <c>null</c>, the service will be retrieved from the <see cref="IServiceLocator"/>.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="propertyChanged"/> is <c>null</c>.</exception>
        public ObjectObserver(INotifyPropertyChanged propertyChanged, object tag = null, IMementoService mementoService = null)
            : base(tag, mementoService)
        {
            Argument.IsNotNull("propertyChanged", propertyChanged);

            Log.Debug("Initializing ObjectObserver for type '{0}'", propertyChanged.GetType().Name);

            _weakEventListener = this.SubscribeToWeakPropertyChangedEvent(propertyChanged, OnPropertyChanged);

            InitializeDefaultValues(propertyChanged);

            Log.Debug("Initialized ObjectObserver for type '{0}'", propertyChanged.GetType().Name);
        }
 public void BindViewModel(INotifyPropertyChanged viewModel, BrowserBridge browser)
 {
     ViewModelDefinition definition = GetViewModelDefinition(viewModel.GetType());
     if (definition == null)
     {
         definition = new ViewModelDefinition(viewModel.GetType(), viewModel.GetType().Name);
         StringBuilder sb = new StringBuilder();
         List<ViewModelDefinition> allDefs = new List<ViewModelDefinition>();
         definition.CollectViewModelDefinitions(allDefs);
         foreach (ViewModelDefinition child in allDefs)
             child.DefineInBrowser(sb);
         InjectFramework(sb);
         browser.InsertScript(sb.ToString());
     }
 }
Example #3
0
 public ValidationTemplate(INotifyPropertyChanged target)
 {
     this.target = target;
     validator = GetValidator(target.GetType());
     validationResult = validator.Validate(target);
     target.PropertyChanged += Validate;
 }
Example #4
0
 public ValidationTemplate(INotifyPropertyChanged target)
 {
     this.target             = target;
     validator               = GetValidator(target.GetType());
     validationResult        = validator.Validate(target);
     target.PropertyChanged += Validate;
 }
        public NotifyPropertyChangedSnapshot(DirtyModelDetector modelDetector, INotifyPropertyChanged snapshotValue)
            : base(modelDetector, snapshotValue)
        {
            if (snapshotValue == null)
            {
                throw new ArgumentNullException("snapshotValue");
            }

            foreach (var propertyInfo in snapshotValue.GetType().GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
            {
                var getMethod = propertyInfo.GetGetMethod();
                if (getMethod != null && getMethod.GetParameters().Any())
                {
                    continue;
                }
                var attributes = propertyInfo.GetCustomAttributes(typeof(IsSerialized), true);
                if (attributes.Length <= 0)
                {
                    continue;
                }

                var snapshot = SnaphotFactory.Create(modelDetector, propertyInfo.GetValue(snapshotValue, null));
                var keyValuePair = new KeyValuePair<PropertyInfo, SnapshotElement>(propertyInfo, snapshot);
                _propertiesSnapshots.Add(propertyInfo.Name, keyValuePair);

            }

            _listenedNotifyPropertyChanged = snapshotValue;
            _listenedNotifyPropertyChanged.PropertyChanged += OnPropertyChanged;
        }
        /// <summary>
        /// Locates the dialog type representing the specified view model in a user interface.
        /// </summary>
        /// <param name="viewModel">The view model to find the dialog type for.</param>
        /// <returns>
        /// The dialog type representing the specified view model in a user interface.
        /// </returns>
        internal static Type LocateDialogType(INotifyPropertyChanged viewModel)
        {
            if (viewModel == null)
                throw new ArgumentNullException("viewModel");

            Type viewModelType = viewModel.GetType();

            Type dialogType = Cache.Get(viewModelType);
            if (dialogType != null)
            {
                return dialogType;
            }

            string dialogName = GetDialogName(viewModelType);
            string dialogAssemblyName = GetAssemblyFullName(viewModelType);

            string dialogFullName = "{0}, {1}".InvariantFormat(
                dialogName,
                dialogAssemblyName);
            
            dialogType = Type.GetType(dialogFullName);
            if (dialogType == null)
                throw new Exception(Resources.DialogTypeMissing.CurrentFormat(dialogFullName));

            Cache.Add(viewModelType, dialogType);
            
            return dialogType;
        }
        /// <summary>
        /// Asserts that property changed is called for the specified property when the value of the property is set
        /// to the specified value.
        /// </summary>
        /// <param name="observableObject">The object that will be observed.</param>
        /// <param name="propertyName">The name of the property that will be observed.</param>
        /// <param name="value">The value to which the property should be set.</param>
        /// <param name="isRaised">Determines wether property changed should be called or not.</param>
        private static void PropertyChangedIsCalled(
            INotifyPropertyChanged observableObject,
            string propertyName,
            object value,
            bool isRaised)
        {
            var propertyFound = false;
            var propertyChangedCalled = false;
            observableObject.PropertyChanged += (sender, args) =>
            {
                if (args.PropertyName == propertyName)
                {
                    propertyChangedCalled = true;
                }
            };

            var properties = observableObject.GetType().GetProperties();

            foreach (var propertyInfo in properties)
            {
                if (propertyInfo.Name == propertyName)
                {
                    propertyInfo.SetValue(observableObject, value, null);
                    propertyFound = true;
                    break;
                }
            }

            Assert.IsTrue(
                propertyFound,
                string.Format("The property {0} could not be found on object {1}.", propertyName, observableObject));

            Assert.AreEqual(isRaised, propertyChangedCalled);
        }
        public static void Notify <TMember>(
            this INotifyPropertyChanged sender,
            PropertyChangedEventHandler handler,
            Expression <Func <TMember> > expression)
        {
            if (sender is null)
            {
                throw new ArgumentNullException("sender");
            }

            if (expression is null)
            {
                throw new ArgumentNullException("expression");
            }

            var body = expression.Body as MemberExpression;

            if (body is null)
            {
                throw new ArgumentException("The expression must target a property or field.", "expression");
            }

            var propertyName = GetPropertyName(body, sender.GetType());

            NotifyCore(sender, handler, propertyName);
        }
Example #9
0
 public MenuItemViewModel(string nameKey, INotifyPropertyChanged nameSource, ICommand command, INotifyPropertyChanged commandParameterSource, string commandParameterName)
     : this("name", new ObservableCollection<IMenuItemViewModel>())
 {
     m_nameKey = nameKey;
       m_nameSource = nameSource;
       m_command = command;
       m_commandParameterSource = commandParameterSource;
       m_commandParameterName = commandParameterName;
       if (m_commandParameterSource != null && m_commandParameterName != null)
       {
     m_commandPropertyInfo = m_commandParameterSource.GetType().GetProperty(m_commandParameterName);
     if (m_commandPropertyInfo != null)
     {
       m_commandParameter = m_commandPropertyInfo.GetValue(m_commandParameterSource);
       m_commandParameterSource.PropertyChanged += CommandParameterSourceOnPropertyChanged;
     }
       }
       if (nameSource != null && nameKey != null)
       {
     m_namePropertyInfo = nameSource.GetType().GetProperty(nameKey);
     if (m_namePropertyInfo != null)
     {
       m_name = m_namePropertyInfo.GetValue(nameSource) as string;
       nameSource.PropertyChanged += NameSourceOnPropertyChanged;
     }
       }
 }
Example #10
0
        /// <summary>
        /// Clears the property binding.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="target">The target.</param>
        /// <param name="sourceProp">The source prop.</param>
        /// <param name="targetProp">The target prop.</param>
        public static void ClearPropertyBinding(Object source, INotifyPropertyChanged target, string sourceProp, string targetProp)
        {
            WeakEntry entry = new WeakEntry(source.GetType(), target.GetType(), sourceProp, targetProp);
            Delegate setAction = GetExpressionAction(entry, source, true);

            WeakSource.UnRegister(source, setAction, targetProp);
        }
        internal NotifyPropertyChangedRecordedElement(IUndoRedoService undoRedoService, INotifyPropertyChanged objAsNotifyPropertyChanged)
            : base(objAsNotifyPropertyChanged)
        {
            if (undoRedoService == null) { throw new ArgumentNullException("undoRedoService"); }
            if (objAsNotifyPropertyChanged == null) { throw new ArgumentNullException("objAsNotifyPropertyChanged"); }

            _objAsNotifyPropertyChanged = objAsNotifyPropertyChanged;
            _objAsNotifyPropertyChanged.PropertyChanged += OnPropertyChanged;

            foreach (var propertyInfo in objAsNotifyPropertyChanged.GetType().GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
            {
                var getMethod = propertyInfo.GetGetMethod();
                if (getMethod != null && getMethod.GetParameters().Any())
                {
                    continue;
                }
                var attributes = propertyInfo.GetCustomAttributes(typeof(IsRecordableAttribute), true);
                if (attributes.Length <= 0)
                {
                    continue;
                }

                var property = PropertyFactory.Create(undoRedoService, objAsNotifyPropertyChanged, (IsRecordableAttribute)attributes[0], propertyInfo);

                _properties.Add(property.Name, property);
            }
        }
Example #12
0
        public PropertyBoundCommand(CommandExecute execute, INotifyPropertyChanged boundTo, string propertyName)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");
            this.execute = execute;

            if (boundTo == null)
                throw new ArgumentNullException("boundTo");
            this.boundTo = boundTo;

            property = boundTo.GetType().GetProperty(propertyName);
            if (property == null)
                throw new ArgumentException("Bad propertyName");

            if (property.PropertyType != typeof(bool))
                throw new ArgumentException("Bad property type");

            propertyGetMethod = property.GetGetMethod();
            if (propertyGetMethod == null)
                throw new ArgumentException("No public get-method found.");

            this.propertyName = propertyName;

            boundTo.PropertyChanged += new PropertyChangedEventHandler(boundTo_PropertyChanged);
        }
Example #13
0
        public static void TestNotifyPropertyChanged(INotifyPropertyChanged obj, string propertyName, object newValue)
        {
            List <string> actualProperties = new List <string>();

            obj.PropertyChanged += (s, e) => actualProperties.Add(e.PropertyName);

            // Test for change
            obj.GetType().GetProperty(propertyName).SetValue(obj, newValue);
            CollectionAssert.Contains(actualProperties, propertyName, "Event call");
            Assert.AreEqual(newValue, obj.GetType().GetProperty(propertyName).GetValue(obj), "Property change");

            // Test for no change
            actualProperties.Clear();
            obj.GetType().GetProperty(propertyName).SetValue(obj, newValue);
            CollectionAssert.DoesNotContain(actualProperties, propertyName, "No event call");
            Assert.AreEqual(newValue, obj.GetType().GetProperty(propertyName).GetValue(obj), "No property change");
        }
    public static void RaisePropertyChanged(this INotifyPropertyChanged @this, [CallerMemberName] string propertyName = null)
    {
        var declaringType               = @this.GetType().GetEvent(nameof(INotifyPropertyChanged.PropertyChanged)).DeclaringType;
        var propertyChangedFieldInfo    = declaringType.GetField(nameof(INotifyPropertyChanged.PropertyChanged), BindingFlags.Instance | BindingFlags.NonPublic);
        var propertyChangedEventHandler = propertyChangedFieldInfo.GetValue(@this) as PropertyChangedEventHandler;

        propertyChangedEventHandler?.Invoke(@this, new PropertyChangedEventArgs(propertyName));
    }
Example #15
0
        internal Resetter(INotifyPropertyChanged settings)
            : base(settings)
        {
            _type = settings.GetType();
            var constructor = _type.GetConstructor(Type.EmptyTypes);

            _defaultSettings = constructor.Invoke(new object[0]);
        }
Example #16
0
        public InstanceInspector(INotifyPropertyChanged inpc)
        {
            _type = inpc.GetType();

            var properties = GetAllProperties(inpc);

            Properties.AddRange(properties.Select(pi => new PropertyInspector(pi, inpc)));
        }
        /// <summary>
        /// Prefer other overloads with x => x.PropertyName for refactor friendliness.
        /// This is faster though.
        /// </summary>
        /// <param name="source"> The source instance to track changes for. </param>
        /// <param name="propertyName"> The name of the property to track. Note that nested properties are not allowed. </param>
        /// <param name="signalInitial"> If true OnNext is called immediately on subscribe. </param>
        public static IObservable <EventPattern <PropertyChangedEventArgs> > ObservePropertyChanged(
            this INotifyPropertyChanged source,
            string propertyName,
            bool signalInitial = true)
        {
            Ensure.NotNull(source, nameof(source));
            Ensure.NotNullOrEmpty(propertyName, nameof(propertyName));
            if (source.GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) == null)
            {
                throw new ArgumentException($"The type {source.GetType()} does not have a property named {propertyName}", propertyName);
            }

            return(ObservePropertyChangedCore(
                       source,
                       propertyName,
                       (sender, args) => new EventPattern <PropertyChangedEventArgs>(sender, args),
                       signalInitial));
        }
Example #18
0
 public ChangeTracker(INotifyPropertyChanged source, PropertiesSettings settings)
 {
     Ensure.NotNull(source, nameof(source));
     Ensure.NotNull(settings, nameof(settings));
     Track.Verify.CanTrackType(source.GetType(), settings);
     this.Settings = settings;
     this.node = ChangeTrackerNode.GetOrCreate(source, settings, true);
     this.node.Value.Changed += this.OnNodeChange;
 }
Example #19
0
        /// <summary>
        /// Get properties which have the <see cref="BlockingPropertyAttribute"/>
        /// </summary>
        /// <param name="self">Class instance that contains the properties</param>
        /// <returns>Collection of Properties that are decorated with the attribute</returns>
        private static IEnumerable <PropertyInfo> GetBlockingProperties(this INotifyPropertyChanged self)
        {
            var properties = self
                             .GetType()
                             .GetProperties(BindingFlags.Instance | BindingFlags.Public)
                             .Where(t => t.GetCustomAttributes(typeof(BlockingPropertyAttribute), false).Length > 0).ToList();

            return(properties);
        }
Example #20
0
        public Type Locate(INotifyPropertyChanged viewModel)
        {
            if (viewModel.GetType() == typeof(ChildViewModel))
            {
                return(typeof(ChildWindow));
            }

            throw new ArgumentException("Unrecognised view model", nameof(viewModel));
        }
 public TwoColumnViewModel(string name, INotifyPropertyChanged attachObject, string property, string format = "", string unit = "")
 {
     Name            = name;
     _format         = format;
     _unit           = unit;
     _attachObject   = attachObject;
     _attachProperty = attachObject.GetType().GetProperty(property);
     _attachObject.PropertyChanged += _attachObject_PropertyChanged;
 }
        ValueNudgerFactory NameAssociationNonFactory(INotifyPropertyChanged container, string propertyName, string description)
        {
            var containerType = container.GetType();
            var property      = containerType.GetProperty(propertyName + "Nudger");
            var nudgerOb      = property.GetValue(container);
            var nudger        = (IValueNudger)nudgerOb;

            return(() => nudger);
        }
Example #23
0
        public ChildChangeListener(INotifyPropertyChanged instance)
        {
            Requires.NotNull(instance, "instance");

            m_value = instance;
            m_type  = m_value.GetType();

            Subscribe();
        }
Example #24
0
 public static void AssertRaisesPropertyChangedFor(this INotifyPropertyChanged obj, string propertyName, object propertyValue)
 {
     using (PropertyChangedEventListener listener = new PropertyChangedEventListener(obj, propertyName))
     {
         Type         MainType = obj.GetType();
         PropertyInfo info     = MainType.GetProperty(propertyName);
         info.SetValue(obj, propertyValue, null);
     }
 }
Example #25
0
 public ChangeTracker(INotifyPropertyChanged source, PropertiesSettings settings)
 {
     Ensure.NotNull(source, nameof(source));
     Ensure.NotNull(settings, nameof(settings));
     Track.Verify.CanTrackType(source.GetType(), settings);
     this.Settings            = settings;
     this.node                = ChangeTrackerNode.GetOrCreate(source, settings, true);
     this.node.Value.Changed += this.OnNodeChange;
 }
Example #26
0
        public ObservableSource(INotifyPropertyChanged itRaisesPropChanged, string pathElement, PathConnectorTypeEnum pathConnectorType, string binderName)
            : this(pathElement, pathConnectorType, false, binderName)
        {
            SourceKind = SourceKindEnum.PropertyObject;
            Data       = itRaisesPropChanged ?? throw new ArgumentNullException($"{nameof(itRaisesPropChanged)} was null when constructing Observable Source.");
            Type       = itRaisesPropChanged.GetType();

            Status = ObservableSourceStatusEnum.Ready;
        }
Example #27
0
        public ValidationTemplate([NotNull] INotifyPropertyChanged target)
        {
            this.target = target;
            validator   = GetValidator(target.GetType());
            var context = new ValidationContext <object>(target);

            validationResult        = validator.Validate(context);
            target.PropertyChanged += Validate;
        }
Example #28
0
 /// <summary>
 /// Sets the property binding.
 /// </summary>
 /// <param name="source">The source.</param>
 /// <param name="target">The target.</param>
 /// <param name="sourceProp">The source prop.</param>
 /// <param name="targetProp">The target prop.</param>
 /// <param name="notify">if set to <c>true</c> update immediately.</param>
 /// <param name="converter">The converter.</param>
 /// <param name="parameter">The converter parameter.</param>
 public static void SetPropertyBinding(Object source, INotifyPropertyChanged target, string sourceProp, string targetProp, bool notify = true, IDataConverter converter = null, object parameter = null)
 {
     WeakEntry entry = new WeakEntry(source.GetType(), target.GetType(), sourceProp, targetProp);
     Delegate setAction = GetExpressionAction(entry, source, true, converter);
     WeakSource wSource = WeakSource.Register(source, target, setAction, targetProp, converter, parameter);
     if (notify)
     {
         wSource.NotifyPropertyChanged(target, targetProp);
     }
 }
Example #29
0
 protected virtual void Trigger(INotifyPropertyChanged inpc, PropertyInfo prop)
 {
     foreach (var handler in inpc.GetType()
              .GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
              .Where(f => f.FieldType == typeof(PropertyChangedEventHandler))
              .Select(f => (PropertyChangedEventHandler)f.GetValue(inpc)).Where(x => x != null))
     {
         handler(inpc, new PropertyChangedEventArgs(prop.Name));
     }
 }
Example #30
0
        /// <summary>
        /// Detaches the event source.
        /// </summary>
        /// <param name="item">The item to detach.</param>
        protected void DetachEventSource([NotNull] INotifyPropertyChanged item)
        {
            var sourceType = item.GetType();

            if (EventSources.TryGetValue(sourceType, out var oldListener) && oldListener.TryGetTarget(out var target))
            {
                target.PropertyChanged -= RelaySource_PropertyChanged;
                EventSources.Remove(sourceType);
            }
        }
        /// <summary> Invokes the specified handler when a property on a property changes, or when the source changes,
        /// and, if the current value differs from the specified default value, at the end of this call. </summary>
        /// <param name="propertyName"> The name of the property on the source. </param>
        /// <param name="propertyOnPropertyName"> The name of the property on the property on the source. </param>
        /// <param name="handler"> The handler to be invoked at the moments listed above. </param>
        /// <param name="defaultValue"> The value that is the default of the property on the property (used as old value when the property containing that property is null).
        /// For value types, you can specify null to indicate the default of the value type. </param>
        public static void Bind(this INotifyPropertyChanged source, string propertyName, string propertyOnPropertyName, PropertyChangedEventHandler handler, object defaultValue)
        {
            Contract.Requires(source != null);
            Contract.Requires(source.GetType().GetProperty(propertyName) != null);

            var  sourcePropertyType     = source.GetType().GetProperty(propertyName).PropertyType;
            Type propertyOnPropertyType = GetPropertyType(sourcePropertyType, propertyOnPropertyName);

            if (ReferenceEquals(defaultValue, null))
            {
                defaultValue = propertyOnPropertyType.GetDefault();
            }
            else
            {
                Contract.Requires(propertyOnPropertyType.IsInstanceOfType(defaultValue));
            }

            Bind(source, propertyName, propertyOnPropertyName, handler, defaultValue, propertyOnPropertyType);
        }
Example #32
0
        public static void VerifyPropertyNamesOnChange(this INotifyPropertyChanged element)
        {
            Contract.Requires(element != null);
            var myType = element.GetType();

            element.PropertyChanged += (sender, args) =>
            {
                Util.ThrowUnless <InvalidOperationException>(myType.HasPublicInstanceProperty(args.PropertyName), "The object '{0}' of type '{1}' raised a property change for '{2}' which isn't a public property on the type.".DoFormat(element, myType, args.PropertyName));
            };
        }
Example #33
0
        public POCOBinding(INotifyPropertyChanged source, string sourcePropertyName, INotifyPropertyChanged target, string targetPropertyName)
        {
            _source = source;
            _sourceProperty = source.GetType().GetProperty(sourcePropertyName);
            _target = target;
            _targetProperty = target.GetType().GetProperty(targetPropertyName);

            _source.PropertyChanged += SourcePropertyChanged;
            _target.PropertyChanged += TargetPropertyChanged;
        }
Example #34
0
        public BindableSource(INotifyPropertyChanged source, string propertyName, BindingMode mode)
        {
            _source       = source;
            _propertyInfo = _source.GetType().GetProperty(propertyName);

            if (mode == BindingMode.TwoWay || mode == BindingMode.OneWay)
            {
                _source.PropertyChanged += SourceOnPropertyChanged;
            }
        }
        NotifyPropertyChangedKVOHelper(INotifyPropertyChanged anObject)
        {
            TargetObject = anObject;
            TargetObject.PropertyChanged += PropertyDidChange;

            if (typeof(INotifyPropertyChanging).IsAssignableFrom(anObject.GetType())) {
                targetSupportsPropertyChanging = true;
                ((INotifyPropertyChanging)anObject).PropertyChanging += PropertyWillChange;
            }
        }
        /// <summary>
        /// Detaches the event source.
        /// </summary>
        /// <param name="item">The item to detach.</param>
        protected void DetachEventSource([NotNull] INotifyPropertyChanged item)
        {
            var sourceType = item.GetType();

            if (EventSources.TryGetValue(sourceType, out var oldListern))
            {
                oldListern?.Detach();
                EventSources.Remove(sourceType);
            }
        }
        /// <summary>
        /// This raises the INotifyPropertyChanged.PropertyChanged event to indicate
        /// a specific property has changed value.
        /// </summary>
        /// <param name="eh">Event Handler</param>
        /// <param name="name">Primary property</param>
        /// <param name="sender">Sender</param>
        public static void RaisePropertyChanged(this INotifyPropertyChanged sender, PropertyChangedEventHandler eh, [CallerMemberName] string name = null)
        {
            Debug.Assert(!string.IsNullOrEmpty(name) &&
                         sender.GetType().GetTypeInfo().GetDeclaredProperty(name) != null);

            if (sender != null && eh != null)
            {
                Invoke(eh, sender, new PropertyChangedEventArgs(name));
            }
        }
Example #38
0
        /// <summary>
        /// 특정 뷰모델에다 Dalog 타입을 위치시키는 메서드
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        public Type Locate(INotifyPropertyChanged viewModel)
        {
            Type viewModelType = viewModel.GetType();

            string dialogFullName = viewModelType.FullName;

            dialogFullName = dialogFullName.Substring(0, dialogFullName.Length - "Model".Length);

            return(viewModelType.Assembly.GetType(dialogFullName));
        }
Example #39
0
        public StubView(INotifyPropertyChanged viewModel)
        {
            viewModel.PropertyChanged += Collect;

            foreach (var commandProperty in viewModel.GetType().GetProperties().Where(prop => typeof(ICommand).IsAssignableFrom(prop.PropertyType)))
            {
                var command = (ICommand)commandProperty.GetValue(viewModel);
                command.CanExecuteChanged += (sender, e) => CommandCanExecuteChangedNotifications.Add(commandProperty.Name);
            }
        }
Example #40
0
 public ValidationTemplate(INotifyPropertyChanged target)
 {
     _target    = target;
     _validator = GetValidator(target.GetType());
     if (_validator != null)
     {
         _validationResult       = _validator.Validate(target);
         target.PropertyChanged += Validate;
     }
 }
Example #41
0
        private IAsyncOperation <ContentDialogResult> ShowContentDialogAsync(
            INotifyPropertyChanged viewModel,
            Type contentDialogType)
        {
            Logger.Write($"Content dialog: {contentDialogType}; View model: {viewModel.GetType()}");

            IContentDialog dialog = CreateContentDialog(contentDialogType, viewModel);

            return(dialog.ShowAsync());
        }
        public static IObservable <PropertyChangedEventArgs> ObservePropertyChangedSlim(this INotifyPropertyChanged source, string name, bool signalInitial = true)
        {
            Ensure.NotNull(source, nameof(source));
            Ensure.NotNullOrEmpty(name, "name");
            if (source.GetType().GetProperty(name) == null)
            {
                throw new ArgumentException($"The type {source.GetType()} does not have a property named {name}", name);
            }

            var observable = source.ObservePropertyChangedSlim()
                             .Where(e => IsPropertyName(e, name));

            if (signalInitial)
            {
                observable = observable.StartWith(new PropertyChangedEventArgs(name));
            }

            return(observable);
        }
        /// <summary>
        /// Sets the property binding.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="target">The target.</param>
        /// <param name="sourceProp">The source prop.</param>
        /// <param name="targetProp">The target prop.</param>
        /// <param name="notify">if set to <c>true</c> update immediately.</param>
        /// <param name="converter">The converter.</param>
        /// <param name="parameter">The converter parameter.</param>
        public static void SetPropertyBinding(Object source, INotifyPropertyChanged target, string sourceProp, string targetProp, bool notify = true, IDataConverter converter = null, object parameter = null)
        {
            WeakEntry  entry     = new WeakEntry(source.GetType(), target.GetType(), sourceProp, targetProp);
            Delegate   setAction = GetExpressionAction(entry, source, true, converter);
            WeakSource wSource   = WeakSource.Register(source, target, setAction, targetProp, converter, parameter);

            if (notify)
            {
                wSource.NotifyPropertyChanged(target, targetProp);
            }
        }
Example #44
0
        private void Show(
            INotifyPropertyChanged ownerViewModel,
            INotifyPropertyChanged viewModel,
            Type dialogType)
        {
            Logger.Write($"Dialog: {dialogType}; View model: {viewModel.GetType()}; Owner: {ownerViewModel.GetType()}");

            IWindow dialog = CreateDialog(dialogType, ownerViewModel, viewModel);

            dialog.Show();
        }
        private static void GetHandlerField(INotifyPropertyChanged changed, out CacheItem[] handlerFields)
        {
            handlerFields = null;
            var type = changed.GetType();
            Func<object, object> instanceGetter;
            if (cached.ContainsKey(type)) {
                handlerFields = cached[type];
            }
            else {
                var result = new List<CacheItem>();
                while (type != null) {
                    var handlerField = type.GetField("PropertyChanged", BindingFlags.Instance | BindingFlags.NonPublic);
                    if (handlerField != null) {
                        result.Add(new CacheItem(handlerField, x => x));
                    }
                    else {
                        var field = type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic).FirstOrDefault(f => f.FieldType.Name == "TrackableEntityAttribute");
                        if (field != null) {
                            var value = field.GetValue(changed);
                            if (value != null) {
                                handlerField = value.GetType().GetField("PropertyChanged", BindingFlags.Instance | BindingFlags.NonPublic);
                                if (handlerField != null)
                                {
                                    result.Add(new CacheItem(handlerField, field, (x, ifield) => ifield.GetValue(x)));
                                }
                            }
                        }
                    }
                    type = type.BaseType;
                }

                Debug.Assert(result.Count() > 0);

                handlerFields = result.ToArray();
                lock (cacheLock) {
                    if (!cached.ContainsKey(changed.GetType()))
                        cached[changed.GetType()] = handlerFields;
                }

            }
        }
Example #46
0
        public InvokeMethodCommand(INotifyPropertyChanged target, MethodInfo method, params object[] parameters)
        {
            if (method == null)
                throw new ArgumentException($"Method on {target} not found!");

            Target = target;
            Method = method;
            Parameters = parameters;
            target.PropertyChanged += Target_PropertyChanged;
            CanExecutePropertyName = $"Can{method.Name}";
            CanExecuteProperty = Target.GetType().GetProperty(CanExecutePropertyName);
        }
        public MakeObjectReactiveHelper(INotifyPropertyChanged hostObject)
        {
            var hostChanging = hostObject as INotifyPropertyChanging;
            if (hostChanging != null) {
                hostChanging.PropertyChanging += (o, e) => _Changing.OnNext(
                    new ObservedChange<object, object>() { Sender = o, PropertyName = e.PropertyName });
            } else {
                this.Log().Error("'{0}' does not implement INotifyPropertyChanging - RxUI may return duplicate change notifications",
                    hostObject.GetType().FullName);
            }

            hostObject.PropertyChanged += (o, e) => _Changed.OnNext(
                new ObservedChange<object, object>() { Sender = o, PropertyName = e.PropertyName });
        }
Example #48
0
		private void AssignAllCommands(INotifyPropertyChanged viewModel)
		{
			var viewModelType = viewModel.GetType();

			var commands =
				viewModelType
					.GetProperties(BindingFlags.Instance | BindingFlags.Public)
					.Where(property =>
						property.PropertyType.EqualsOrSubclassOf<ICommand>() &&
						property.GetValue(viewModel, null) == null)
					.ToList();

			var errors = commands.SelectMany(property => AssignCommand(viewModel, property)).ToList();

			if (!errors.Any())
			{
				return;
			}

			errors.Insert(0, "Issues found on type {0}:".NamedFormat(viewModel.GetType().Name));
			var message = errors.JoinMultiLine();

			new InvalidOperationException(message).Throw();
		}
Example #49
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ObjectObserver"/> class.
        /// </summary>
        /// <param name="propertyChanged">The property changed.</param>
        /// <param name="tag">The tag.</param>
        /// <param name="mementoService">The memento service. If <c>null</c>, the service will be retrieved from the <see cref="IServiceLocator"/>.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="propertyChanged"/> is <c>null</c>.</exception>
        public ObjectObserver(INotifyPropertyChanged propertyChanged, object tag = null, IMementoService mementoService = null)
            : base(tag, mementoService)
        {
            Argument.IsNotNull("propertyChanged", propertyChanged);

            var propertyChangedType = propertyChanged.GetType();

            Log.Debug("Initializing ObjectObserver for type '{0}'", propertyChangedType.Name);

            _object = propertyChanged;
            _object.PropertyChanged += OnPropertyChanged;

            InitializeDefaultValues(propertyChanged);

            Log.Debug("Initialized ObjectObserver for type '{0}'", propertyChangedType.Name);
        }
Example #50
0
 public MenuItemViewModel(string name, ICommand command, INotifyPropertyChanged commandParameterSource = null, string commandParameterName= null)
     : this(name, new ObservableCollection<IMenuItemViewModel>())
 {
     m_command = command;
       m_commandParameterSource = commandParameterSource;
       m_commandParameterName = commandParameterName;
       if (m_commandParameterSource != null && m_commandParameterName != null)
       {
     m_commandPropertyInfo = m_commandParameterSource.GetType().GetProperty(m_commandParameterName);
     if (m_commandPropertyInfo != null)
     {
       m_commandParameter = m_commandPropertyInfo.GetValue(m_commandParameterSource);
       m_commandParameterSource.PropertyChanged += CommandParameterSourceOnPropertyChanged;
     }
       }
 }
 public static IDisposable BindPropertyToObject(
     INotifyPropertyChanged source, 
     string propertyName, 
     object target,
     Action<object, object> setTargetValue,
     Func<object, IObservable<object>> createTargetObservable,
     Func<object> getInitialValue,
     Func<object, object> getCurrentValue)
 {
     var propertyObs = source.ObservableForProperty(new string[] { propertyName });
     propertyObs.Subscribe(e => {
         setTargetValue(target, e.Value);
     });
     var targetObs = createTargetObservable(target);
     var propertySetter = source.GetType().GetProperty(propertyName).GetSetMethod();
     return Observable.Return(getInitialValue()).Concat(targetObs).Subscribe(e => {
         propertySetter.Invoke(source, new object[] { getCurrentValue(target) });
     });
 }
		static void SetupPropertyChanged(IList<object> closed, INotifyPropertyChanged component, ChangeOccuredHandler changedHandler)
		{
			if (closed.Contains(component)) return; // event was already registered

			closed.Add(component); //adds the property that is to be processed

			//sets the property changed event if the property isn't a collection
			if (!(component is INotifyCollectionChanged))
				component.PropertyChanged += (sender, e) => changedHandler(sender, e.PropertyName);

			/*			
         * If the component is an enumerable there are two steps. First check to see if it supports the INotifyCollectionChanged event.
         * If it supports it add and handler on to this object to support notification.  Next iterate through the collection of objects
         * to add hook up their PropertyChangedEvent.
         * 
         * If the component isn't a collection then iterate through its properties and attach the changed handler to the properties.
         */
			if (component is IEnumerable<object>)
			{
				if (component is INotifyCollectionChanged)
				{
					//((INotifyCollectionChanged)component).CollectionChanged += collectionHandler;
					((INotifyCollectionChanged)component).CollectionChanged += (sender, e) => changedHandler(sender, "collection");
				}

				foreach (object obj in component as IEnumerable<object>)
				{
					if (obj is INotifyPropertyChanged)
						SetupPropertyChanged(closed, (INotifyPropertyChanged)obj, changedHandler);
				}
			}
			else
			{
				foreach (PropertyInfo info in component.GetType().GetProperties())
				{
					var propertyValue = info.GetValue(component, new object[] { });
					var inpc = propertyValue as INotifyPropertyChanged;
					if (inpc == null) continue;
					SetupPropertyChanged(closed, inpc, changedHandler);
				}
			}
		}
        public PropertyCollection GetProperties(INotifyPropertyChanged obj)
        {
            var visibleProperties =
                from p in obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)
                where p.IsDefined(typeof(UIVisibleAttribute))
                select p;

            var collection = new PropertyCollection();

            foreach (var item in visibleProperties)
            {
                var propertyValue = (PropertyValue)Activator.CreateInstance(
                    typeof(PropertyValue<>).MakeGenericType(item.PropertyType),
                    obj,
                    item);

                collection.Items.Add(propertyValue);
            }

            return collection;
        }
Example #54
0
        /// <summary>
        /// Verifies that the provided object raised <see cref="INotifyPropertyChanged.PropertyChanged"/>
        /// as a result of executing the given test code.
        /// </summary>
        /// <param name="object">The object which should raise the notification</param>
        /// <param name="propertyName">The property name for which the notification should be raised</param>
        /// <param name="testCode">The test code which should cause the notification to be raised</param>
        /// <param name="expectedValue">The expected value of the property as the notification is raised</param>
        /// <exception cref="PropertyChangedException">Thrown when the notification is not raised, or if 
        /// given property was not updated with expected value when notification was raised.</exception>
        public static void PropertyChanged(INotifyPropertyChanged @object, string propertyName, Action testCode, object expectedValue = null)
        {
            Assert.GuardArgumentNotNull("object", @object);
            Assert.GuardArgumentNotNull("testCode", testCode);

            bool propertyChangeHappened = false;
            object actualValue = null;

            PropertyChangedEventHandler handler = (sender, args) =>
            {
                if (propertyName.Equals(args.PropertyName, StringComparison.OrdinalIgnoreCase))
                {
                    propertyChangeHappened = true;
                    if (expectedValue != null)
                    {
                        actualValue = @object.GetType().GetRuntimeProperties().Single(property => property.Name.Equals(propertyName, StringComparison.OrdinalIgnoreCase)).GetValue(@object);
                    }
                }
            };

            @object.PropertyChanged += handler;

            try
            {
                testCode();
                if (!propertyChangeHappened)
                    throw new PropertyChangedException(propertyName);

                if (expectedValue != null && !expectedValue.Equals(actualValue))
                    throw new PropertyChangedException(propertyName, expectedValue);
            }
            finally
            {
                @object.PropertyChanged -= handler;
            }
        }
Example #55
0
 internal ViewModelInstance InstantiateInBrowser(INotifyPropertyChanged instance, BrowserBridge browser)
 {
     ViewModelInstance result = null;
     viewModelInstancesByViewModel.TryGetValue(instance, out result);
     if (result == null)
     {
         result = new ViewModelInstance(instance, GetViewModelDefinition(instance.GetType()), browser);
         result.RefCount = 1;
         viewModelInstancesById[result.Id] = result;
         viewModelInstancesByViewModel[instance] = result;
         result.InitializeProperties();
         browser.ExecuteScriptFunction("handleViewModelCreated", instance.GetType().Name, result.Id.ToString("N"));
     }
     else
         result.RefCount++;
     return result;
 }
Example #56
0
 public InvokeMethodCommand(INotifyPropertyChanged target, string method, params object[] parameters)
     : this(target, target.GetType().GetMethod(method), parameters)
 {
 }
Example #57
0
        public ObjectPayload(Guid clientId, INotifyPropertyChanged sharedObject, Guid objectId, string objectName)
            : base(objectName, objectId, clientId)
        {
            Type sharedObjectType = sharedObject.GetType();
#if IL2JS
            this.Type = sharedObject.GetType().Name;            
#else
            this.Type = sharedObjectType.AssemblyQualifiedName;
#endif
            this.Attributes = new SharedAttributes(sharedObjectType);
            this.SharedProperties = new SharedPropertyDictionary(sharedObject.GetSharedProperties(clientId));
        }
        /// <summary>
        /// Constructor with item</summary>
        /// <param name="instance">Item whose property value change is listened to</param>
        public ChildChangeListener(INotifyPropertyChanged instance)
        {
            Requires.NotNull(instance, "instance");

            m_value = instance;
            m_type = m_value.GetType();

            Subscribe();
        }
Example #59
0
        /// <summary>
        /// Update the properties of the target object with the contents of the ObjectPayload
        /// </summary>
        /// <param name="target"></param>
        /// <param name="data"></param>
        private void UpdateProperties(INotifyPropertyChanged target, ObjectPayload data)
        {
            this.client.VerifyAccess();

            Type targetType = target.GetType();

            IJsObject jsDictionary = target as IJsObject;
            if (jsDictionary != null)
            {
                // In case of JsObservableDictionary, we want to treat the properties in this payload as items of the dictionary
                foreach (SharedProperty sharedProp in data.SharedProperties.Values)
                {
                    jsDictionary[sharedProp.Name] = Json.ReadObject(DynamicTypeMapping.Instance.GetTypeFromValue(sharedProp.PropertyType), sharedProp.Value);
                }
            }
            else
            {
                foreach (SharedProperty sharedProp in data.SharedProperties.Values)
                {
                    Json.AssignProperty(target, sharedProp.Name, sharedProp.Value);
                }
            }
        }
Example #60
0
        /// <summary>
        /// Constructor used for outgoing codepaths
        /// </summary>
        /// <param name="client"></param>
        /// <param name="name"></param>
        /// <param name="id"></param>
        /// <param name="obj"></param>
        private ObjectEntry(SharedObjectsClient client, string name, Guid id, INotifyPropertyChanged obj)
        {
            this.client = client;
            this.IgnoreChanges = false;
            
            this.Object = obj;
            this.Id = id;
            this.Name = name ?? this.Id.ToString();
            IJsObject jsObj = obj as IJsObject; // do this here so we only do the cast once
            this.IsDynamic = jsObj != null;
            this.Parents = new Dictionary<Guid, ParentEntry>();
            this.Type = obj.GetType();

            this.Attributes = new SharedAttributes(obj.GetType());

            if(jsObj != null)
            {
                this.Properties = new SharedPropertyDictionary(jsObj.GetSharedProperties(this.client.ClientId));
            }
            else
            {
                this.Properties = new SharedPropertyDictionary(obj.GetSharedProperties(this.client.ClientId));
            }
        }