IsValidValue() 공개 메소드

public IsValidValue ( object value ) : bool
value object
리턴 bool
예제 #1
0
        private static DependencyProperty Register(DependencyPropertyHashKey key, Type propertyType, PropertyMetadata metadata, ValidateValueCallback validateValueCallback, bool isAttached, bool isReadOnly)
        {
            if (metadata == null)
            {
                metadata = new PropertyMetadata();
            }

            if (metadata.DefaultValue == null && propertyType.GetIsValueType())
            {
                metadata.DefaultValue = Activator.CreateInstance(propertyType);
            }

            if (metadata.DefaultValue != null && !propertyType.IsInstanceOfType(metadata.DefaultValue))
            {
                metadata.DefaultValue = ConvertDefaultValue(key, metadata.DefaultValue, propertyType);
            }

            DependencyProperty property = new DependencyProperty(key, propertyType, metadata, validateValueCallback, isAttached, isReadOnly);

            if (!property.IsValidValue(metadata.DefaultValue))
            {
                throw new Granular.Exception("Default value validation of dependency property \"{0}.{1}\" failed", key.Owner.Name, key.Name);
            }

            AddRegisteredProperty(key, property);

            return(property);
        }
예제 #2
0
        //-----------------------------------------------------
        // 
        //  Constructors 
        //
        //----------------------------------------------------- 

        #region Constructors

        private DPTypeDescriptorContext(DependencyProperty property, object propertyValue) 
        {
            Invariant.Assert(property != null, "property == null"); 
            Invariant.Assert(propertyValue != null, "propertyValue == null"); 
            Invariant.Assert(property.IsValidValue(propertyValue), "propertyValue must be of suitable type for the given dependency property");
 
            _property = property;
            _propertyValue = propertyValue;
        }
예제 #3
0
        /// <summary>
        ///     Seals this setter
        /// </summary>
        internal override void Seal()
        {
            // Do the validation that can't be done until we know all of the property
            // values.

            DependencyProperty dp    = Property;
            object             value = ValueInternal;

            if (dp == null)
            {
                throw new ArgumentException(SR.Get(SRID.NullPropertyIllegal, "Setter.Property"));
            }

            if (String.IsNullOrEmpty(TargetName))
            {
                // Setter on container is not allowed to affect the StyleProperty.
                if (dp == FrameworkElement.StyleProperty)
                {
                    throw new ArgumentException(SR.Get(SRID.StylePropertyInStyleNotAllowed));
                }
            }

            // Value needs to be valid for the DP, or a deferred reference, or one of the supported
            // markup extensions.

            if (!dp.IsValidValue(value))
            {
                // The only markup extensions supported by styles is resources and bindings.
                if (value is MarkupExtension)
                {
                    if (!(value is DynamicResourceExtension) && !(value is System.Windows.Data.BindingBase))
                    {
                        throw new ArgumentException(SR.Get(SRID.SetterValueOfMarkupExtensionNotSupported,
                                                           value.GetType().Name));
                    }
                }

                else if (!(value is DeferredReference))
                {
                    throw new ArgumentException(SR.Get(SRID.InvalidSetterValue, value, dp.OwnerType, dp.Name));
                }
            }

            // Freeze the value for the setter
            StyleHelper.SealIfSealable(_value);

            base.Seal();
        }
예제 #4
0
파일: Condition.cs 프로젝트: JianwenSun/cc
        /// <summary>
        ///     Constructor for creating a Condition with the given property
        /// and value instead of creating an empty one and setting values later.
        /// </summary>
        /// <remarks>
        ///     This constructor does parameter validation, which before doesn't
        /// happen until Seal() is called.  We can do it here because we get
        /// both at the same time.
        /// </remarks>
        public Condition( DependencyProperty conditionProperty, object conditionValue, string sourceName )
        {
            if( conditionProperty == null )
            {
                throw new ArgumentNullException("conditionProperty");
            }

            if( !conditionProperty.IsValidValue( conditionValue ) )
            {
                throw new ArgumentException(SR.Get(SRID.InvalidPropertyValue, conditionValue, conditionProperty.Name));
            }

            _property = conditionProperty;
            Value    = conditionValue;
            _sourceName = sourceName;
        }
예제 #5
0
        /// <summary>
        ///     Constructor for creating a Condition with the given property
        /// and value instead of creating an empty one and setting values later.
        /// </summary>
        /// <remarks>
        ///     This constructor does parameter validation, which before doesn't
        /// happen until Seal() is called.  We can do it here because we get
        /// both at the same time.
        /// </remarks>
        public Condition(DependencyProperty conditionProperty, object conditionValue, string sourceName)
        {
            if (conditionProperty == null)
            {
                throw new ArgumentNullException(nameof(conditionProperty));
            }

            if (!conditionProperty.IsValidValue(conditionValue))
            {
                throw new ArgumentException(SR.Get(SRID.InvalidPropertyValue, conditionValue, conditionProperty.Name));
            }

            _property   = conditionProperty;
            Value       = conditionValue;
            _sourceName = sourceName;
        }
예제 #6
0
 /// <summary>Initializes a new instance of the <see cref="T:System.Windows.Condition" /> class with the specified property, value, and the name of the source object.</summary>
 /// <param name="conditionProperty">The property of the condition.</param>
 /// <param name="conditionValue">The value of the condition.</param>
 /// <param name="sourceName">
 ///       x:Name of the object with the <paramref name="conditionProperty" />.</param>
 // Token: 0x0600034D RID: 845 RVA: 0x000095AC File Offset: 0x000077AC
 public Condition(DependencyProperty conditionProperty, object conditionValue, string sourceName)
 {
     if (conditionProperty == null)
     {
         throw new ArgumentNullException("conditionProperty");
     }
     if (!conditionProperty.IsValidValue(conditionValue))
     {
         throw new ArgumentException(SR.Get("InvalidPropertyValue", new object[]
         {
             conditionValue,
             conditionProperty.Name
         }));
     }
     this._property   = conditionProperty;
     this.Value       = conditionValue;
     this._sourceName = sourceName;
 }
예제 #7
0
        // Token: 0x06000894 RID: 2196 RVA: 0x0001BE34 File Offset: 0x0001A034
        internal override void Seal()
        {
            DependencyProperty property      = this.Property;
            object             valueInternal = this.ValueInternal;

            if (property == null)
            {
                throw new ArgumentException(SR.Get("NullPropertyIllegal", new object[]
                {
                    "Setter.Property"
                }));
            }
            if (string.IsNullOrEmpty(this.TargetName) && property == FrameworkElement.StyleProperty)
            {
                throw new ArgumentException(SR.Get("StylePropertyInStyleNotAllowed"));
            }
            if (!property.IsValidValue(valueInternal))
            {
                if (valueInternal is MarkupExtension)
                {
                    if (!(valueInternal is DynamicResourceExtension) && !(valueInternal is BindingBase))
                    {
                        throw new ArgumentException(SR.Get("SetterValueOfMarkupExtensionNotSupported", new object[]
                        {
                            valueInternal.GetType().Name
                        }));
                    }
                }
                else if (!(valueInternal is DeferredReference))
                {
                    throw new ArgumentException(SR.Get("InvalidSetterValue", new object[]
                    {
                        valueInternal,
                        property.OwnerType,
                        property.Name
                    }));
                }
            }
            StyleHelper.SealIfSealable(this._value);
            base.Seal();
        }
예제 #8
0
        private void SetValue()
        {
            object value = GetAnimationValue(true);

            if (value == ObservableValue.UnsetValue)
            {
                value = GetCurrentValue(true);
            }

            if (value == ObservableValue.UnsetValue)
            {
                value = GetBaseValue(true);
            }

            if (value == ObservableValue.UnsetValue || !dependencyProperty.IsValidValue(value))
            {
                value = defaultValue;
            }

            observableValue.Value = value;
        }
예제 #9
0
        private void SetValue(DependencyProperty dependencyProperty, DependencyPropertyKey dependencyPropertyKey, object value, bool setCurrentValue = false, BaseValueSource source = BaseValueSource.Unknown)
        {
            VerifyReadOnlyProperty(dependencyProperty, dependencyPropertyKey);

            IExpressionProvider newExpressionProvider = value as IExpressionProvider;

            if (newExpressionProvider == null && !dependencyProperty.IsValidValue(value))
            {
                return; // invalid value
            }

            IDependencyPropertyValueEntry entry = GetInitializedValueEntry(dependencyProperty);

            IExpression oldExpression = setCurrentValue ?
                                        entry.GetBaseValue(false) as IExpression : // current value may be set in the top priority expression
                                        entry.GetBaseValue((int)source, false) as IExpression;

            if (newExpressionProvider != null)
            {
                value = newExpressionProvider.CreateExpression(this, dependencyProperty);
            }
            else if (oldExpression != null && oldExpression.SetValue(value))
            {
                return; // value (current or not) was set in the existing expression, nothing else to do
            }

            if (setCurrentValue)
            {
                entry.SetCurrentValue(value);
                return; // base value isn't changed
            }

            if (oldExpression is IDisposable) // expression is being replaced
            {
                ((IDisposable)oldExpression).Dispose();
            }

            entry.SetBaseValue((int)source, value);
            entry.ClearCurrentValue();
        }
예제 #10
0
        static object ConvertValue(object value, DependencyProperty dp, out Exception e) 
        { 
            object result;
            e = null; 

            if (value == DependencyProperty.UnsetValue || dp.IsValidValue(value))
            {
                result = value; 
            }
            else 
            { 
                result = null;  // placeholder to keep compiler happy
                // if value isn't the right type, use a type converter to get a better value 
                bool success = false;
                TypeConverter converter = DefaultValueConverter.GetConverter(dp.PropertyType);
                if (converter != null && converter.CanConvertFrom(value.GetType()))
                { 
                    // PreSharp uses message numbers that the C# compiler doesn't know about.
                    // Disable the C# complaints, per the PreSharp documentation. 
                    #pragma warning disable 1634, 1691 

                    // PreSharp complains about catching NullReference (and other) exceptions. 
                    // It doesn't recognize that IsCriticalException() handles these correctly.
                    #pragma warning disable 56500

                    try 
                    {
                        result = converter.ConvertFrom(null, CultureInfo.InvariantCulture, value); 
                        success = dp.IsValidValue(result); 
                    }
 
                    // Catch all exceptions.  If we can't convert the fallback value, it doesn't
                    // matter why not;  we should always use the default value instead.
                    // (See bug 1853628 for an example of a converter that throws
                    // an exception not mentioned in the documentation for ConvertFrom.) 
                    catch (Exception ex)
                    { 
                        e = ex; 
                    }
                    catch // non CLS compliant exception 
                    {
                    }

                    #pragma warning restore 56500 
                    #pragma warning restore 1634, 1691
                } 
 
                if (!success)
                { 
                    // if can't convert it, don't use it
                    result = DefaultValueObject;
                }
            } 

            return result; 
        } 
예제 #11
0
        /// <summary>
        ///     The common code shared by all variants of SetValue 
        /// </summary> 
        // Takes metadata from caller because most of them have already retrieved it
        //  for their own purposes, avoiding the duplicate GetMetadata call. 
        private void SetValueCommon(
            DependencyProperty  dp,
            object              value,
            PropertyMetadata    metadata, 
            bool                coerceWithDeferredReference,
            bool                coerceWithCurrentValue, 
            OperationType       operationType, 
            bool                isInternal)
        { 
            if (IsSealed)
            {
                throw new InvalidOperationException(SR.Get(SRID.SetOnReadOnlyObjectNotAllowed, this));
            } 

            Expression newExpr = null; 
            DependencySource[] newSources = null; 

            EntryIndex entryIndex = LookupEntry(dp.GlobalIndex); 

            // Treat Unset as a Clear
            if( value == DependencyProperty.UnsetValue )
            { 
                // Parameters should have already been validated, so we call
                //  into the private method to avoid validating again. 
                ClearValueCommon(entryIndex, dp, metadata); 
                return;
            } 

            // Validate the "value" against the DP.
            bool isDeferredReference = false;
            bool newValueHasExpressionMarker = (value == ExpressionInAlternativeStore); 

            // First try to validate the value; only after this validation fails should we 
            // do the more expensive checks (type checks) for the less common scenarios 
            if (!newValueHasExpressionMarker)
            { 
                bool isValidValue = isInternal ? dp.IsValidValueInternal(value) : dp.IsValidValue(value);

                // for properties of type "object", we have to always check for expression & deferredreference
                if (!isValidValue || dp.IsObjectType) 
                {
                    // 2nd most common is expression 
                    newExpr = value as Expression; 
                    if (newExpr != null)
                    { 
                        // For Expressions, perform additional validation
                        // Make sure Expression is "attachable"
                        if (!newExpr.Attachable)
                        { 
                            throw new ArgumentException(SR.Get(SRID.SharingNonSharableExpression));
                        } 
 
                        // Check dispatchers of all Sources
                        // CALLBACK 
                        newSources = newExpr.GetSources();
                        ValidateSources(this, newSources, newExpr);
                    }
                    else 
                    {
                        // and least common is DeferredReference 
                        isDeferredReference = (value is DeferredReference); 
                        if (!isDeferredReference)
                        { 
                            if (!isValidValue)
                            {
                                // it's not a valid value & it's not an expression, so throw
                                throw new ArgumentException(SR.Get(SRID.InvalidPropertyValue, value, dp.Name)); 
                            }
                        } 
                    } 
                }
            } 

            // Get old value
            EffectiveValueEntry oldEntry;
            if (operationType == OperationType.ChangeMutableDefaultValue) 
            {
                oldEntry = new EffectiveValueEntry(dp, BaseValueSourceInternal.Default); 
                oldEntry.Value = value; 
            }
            else 
            {
                oldEntry = GetValueEntry(entryIndex, dp, metadata, RequestFlags.RawEntry);
            }
 
            // if there's an expression in some other store, fetch it now
            Expression currentExpr = 
                    (oldEntry.HasExpressionMarker)  ? _getExpressionCore(this, dp, metadata) 
                  : (oldEntry.IsExpression)         ? (oldEntry.LocalValue as Expression)
                  :                                   null; 

            // Allow expression to store value if new value is
            // not an Expression, if applicable
 
            bool handled = false;
            if ((currentExpr != null) && (newExpr == null)) 
            { 
                // Resolve deferred references because we haven't modified
                // the expression code to work with DeferredReference yet. 
                if (isDeferredReference)
                {
                    value = ((DeferredReference) value).GetValue(BaseValueSourceInternal.Local);
                } 

                // CALLBACK 
                handled = currentExpr.SetValue(this, dp, value); 
                entryIndex = CheckEntryIndex(entryIndex, dp.GlobalIndex);
            } 

            // Create the new effective value entry
            EffectiveValueEntry newEntry;
            if (handled) 
            {
                // If expression handled set, then done 
                if (entryIndex.Found) 
                {
                    newEntry = _effectiveValues[entryIndex.Index]; 
                }
                else
                {
                    // the expression.SetValue resulted in this value being removed from the table; 
                    // use the default value.
                    newEntry = EffectiveValueEntry.CreateDefaultValueEntry(dp, metadata.GetDefaultValue(this, dp)); 
                } 

                coerceWithCurrentValue = false; // expression already handled the control-value 
            }
            else
            {
                // allow a control-value to coerce an expression value, when the 
                // expression didn't handle the value
                if (coerceWithCurrentValue && currentExpr != null) 
                { 
                    currentExpr = null;
                } 

                newEntry = new EffectiveValueEntry(dp, BaseValueSourceInternal.Local);

                // detach the old expression, if applicable 
                if (currentExpr != null)
                { 
                    // CALLBACK 
                    DependencySource[] currentSources = currentExpr.GetSources();
 
                    UpdateSourceDependentLists(this, dp, currentSources, currentExpr, false);  // Remove

                    // CALLBACK
                    currentExpr.OnDetach(this, dp); 
                    currentExpr.MarkDetached();
                    entryIndex = CheckEntryIndex(entryIndex, dp.GlobalIndex); 
                } 

                // attach the new expression, if applicable 
                if (newExpr == null)
                {
                    // simple local value set
                    newEntry.HasExpressionMarker = newValueHasExpressionMarker; 
                    newEntry.Value = value;
                } 
                else 
                {
                    Debug.Assert(!coerceWithCurrentValue, "Expression values not supported in SetCurrentValue"); 

                    // First put the expression in the effectivevalueentry table for this object;
                    // this allows the expression to update the value accordingly in OnAttach
                    SetEffectiveValue(entryIndex, dp, dp.GlobalIndex, metadata, newExpr, BaseValueSourceInternal.Local); 

                    // Before the expression is attached it has default value 
                    object defaultValue = metadata.GetDefaultValue(this, dp); 
                    entryIndex = CheckEntryIndex(entryIndex, dp.GlobalIndex);
                    SetExpressionValue(entryIndex, defaultValue, newExpr); 
                    UpdateSourceDependentLists(this, dp, newSources, newExpr, true);  // Add

                    newExpr.MarkAttached();
 
                    // CALLBACK
                    newExpr.OnAttach(this, dp); 
 
                    // the attach may have added entries in the effective value table ...
                    // so, update the entryIndex accordingly. 
                    entryIndex = CheckEntryIndex(entryIndex, dp.GlobalIndex);

                    newEntry = EvaluateExpression(
                            entryIndex, 
                            dp,
                            newExpr, 
                            metadata, 
                            oldEntry,
                            _effectiveValues[entryIndex.Index]); 

                    entryIndex = CheckEntryIndex(entryIndex, dp.GlobalIndex);
                }
            } 

            UpdateEffectiveValue( 
                entryIndex, 
                dp,
                metadata, 
                oldEntry,
                ref newEntry,
                coerceWithDeferredReference,
                coerceWithCurrentValue, 
                operationType);
        } 
예제 #12
0
        /// <summary>
        ///     This overload of GetValue assumes that entryIndex is valid. 
        ///      It also does not do the check storage on the InheritanceParent.
        /// </summary> 
        private EffectiveValueEntry GetEffectiveValue( 
            EntryIndex          entryIndex,
            DependencyProperty  dp, 
            RequestFlags        requests)
        {
            EffectiveValueEntry entry = _effectiveValues[entryIndex.Index];
            EffectiveValueEntry effectiveEntry = entry.GetFlattenedEntry(requests); 

            if (((requests & (RequestFlags.DeferredReferences | RequestFlags.RawEntry)) != 0) || !effectiveEntry.IsDeferredReference) 
            { 
                return effectiveEntry;
            } 

            if (!entry.HasModifiers)
            {
                // For thread-safety, sealed DOs can't modify _effectiveValues. 
                Debug.Assert(!DO_Sealed, "A Sealed DO cannot be modified");
 
                if (!entry.HasExpressionMarker) 
                {
                    // The value for this property was meant to come from a dictionary 
                    // and the creation of that value had been deferred until this
                    // time for better performance. Now is the time to actually instantiate
                    // this value by querying it from the dictionary. Once we have the
                    // value we can actually replace the deferred reference marker 
                    // with the actual value.
                    DeferredReference reference = (DeferredReference)entry.Value; 
                    object value = reference.GetValue(entry.BaseValueSourceInternal); 

                    if (!dp.IsValidValue(value)) 
                    {
                        throw new InvalidOperationException(SR.Get(SRID.InvalidPropertyValue, value, dp.Name));
                    }
 
                    // Make sure the entryIndex is in [....] after
                    // the inflation of the deferred reference. 
                    entryIndex = CheckEntryIndex(entryIndex, dp.GlobalIndex); 

                    entry.Value = value; 

                    _effectiveValues[entryIndex.Index] = entry;
                    return entry;
                } 
            }
            else 
            { 
                // The value for this property was meant to come from a dictionary
                // and the creation of that value had been deferred until this 
                // time for better performance. Now is the time to actually instantiate
                // this value by querying it from the dictionary. Once we have the
                // value we can actually replace the deferred reference marker
                // with the actual value. 

                ModifiedValue modifiedValue = entry.ModifiedValue; 
                DeferredReference reference = null; 
                bool referenceFromExpression = false;
 
                if (entry.IsCoercedWithCurrentValue)
                {
                    if (!entry.IsAnimated)
                    { 
                        reference = modifiedValue.CoercedValue as DeferredReference;
                    } 
                } 

                if (reference == null && entry.IsExpression) 
                {
                    if (!entry.IsAnimated && !entry.IsCoerced)
                    {
                        reference = (DeferredReference) modifiedValue.ExpressionValue; 
                        referenceFromExpression = true;
                    } 
                } 

                Debug.Assert(reference != null, "the only modified values that can have deferredreferences are (a) expression, (b) coerced control value"); 
                if (reference == null)
                {
                    return effectiveEntry;
                } 

                object value = reference.GetValue(entry.BaseValueSourceInternal); 
 
                if (!dp.IsValidValue(value))
                { 
                    throw new InvalidOperationException(SR.Get(SRID.InvalidPropertyValue, value, dp.Name));
                }

                // Make sure the entryIndex is in [....] after 
                // the inflation of the deferred reference.
                entryIndex = CheckEntryIndex(entryIndex, dp.GlobalIndex); 
 
                if (referenceFromExpression)
                { 
                    entry.SetExpressionValue(value, modifiedValue.BaseValue);
                }
                else
                { 
                    entry.SetCoercedValue(value, null, true /* skipBaseValueChecks */, entry.IsCoercedWithCurrentValue);
                } 
 
                _effectiveValues[entryIndex.Index] = entry;
 
                effectiveEntry.Value = value;
            }
            return effectiveEntry;
        } 
예제 #13
0
        private EffectiveValueEntry EvaluateExpression( 
            EntryIndex entryIndex,
            DependencyProperty dp, 
            Expression expr,
            PropertyMetadata metadata,
            EffectiveValueEntry oldEntry,
            EffectiveValueEntry newEntry) 
        {
            object value = expr.GetValue(this, dp); 
            bool isDeferredReference = false; 

            if (value != DependencyProperty.UnsetValue && value != Expression.NoValue) 
            {
                isDeferredReference = (value is DeferredReference);
                if (!isDeferredReference && !dp.IsValidValue(value))
                { 
#region EventTracing
#if VERBOSE_PROPERTY_EVENT 
                    if (isDynamicTracing) 
                    {
                        if (EventTrace.IsEnabled(EventTrace.Flags.performance, EventTrace.Level.verbose)) 
                        {
                            EventTrace.EventProvider.TraceEvent(EventTrace.PROPERTYGUID,
                                                                MS.Utility.EventType.EndEvent,
                                                                EventTrace.PROPERTYVALIDATION, 0xFFF ); 
                        }
                    } 
#endif 
#endregion EventTracing
                    throw new InvalidOperationException(SR.Get(SRID.InvalidPropertyValue, value, dp.Name)); 
                }
            }
            else
            { 
                if (value == Expression.NoValue)
                { 
                    // The expression wants to "hide".  First set the 
                    // expression value to NoValue to indicate "hiding".
                    newEntry.SetExpressionValue(Expression.NoValue, expr); 

                    // Next, get the expression value some other way.
                    if (!dp.ReadOnly)
                    { 
                        EvaluateBaseValueCore(dp, metadata, ref newEntry);
                        value = newEntry.GetFlattenedEntry(RequestFlags.FullyResolved).Value; 
                    } 
                    else
                    { 
                        value = DependencyProperty.UnsetValue;
                    }
                }
 
                // if there is still no value, use the default
                if (value == DependencyProperty.UnsetValue) 
                { 
                    value = metadata.GetDefaultValue(this, dp);
                } 
            }

            // Set the expr and its evaluated value into
            // the _effectiveValues cache 
            newEntry.SetExpressionValue(value, expr);
            return newEntry; 
        } 
예제 #14
0
        private void ProcessCoerceValue(
            DependencyProperty dp, 
            PropertyMetadata metadata,
            ref EntryIndex entryIndex,
            ref int targetIndex,
            ref EffectiveValueEntry newEntry, 
            ref EffectiveValueEntry oldEntry,
            ref object oldValue, 
            object baseValue, 
            object controlValue,
            CoerceValueCallback coerceValueCallback, 
            bool coerceWithDeferredReference,
            bool coerceWithCurrentValue,
            bool skipBaseValueChecks)
        { 
            if (newEntry.IsDeferredReference)
            { 
                Debug.Assert(!(newEntry.IsCoerced && !newEntry.IsCoercedWithCurrentValue) && 
                    !newEntry.IsAnimated, "Coerced or Animated value cannot be a deferred reference");
 
                // Allow values to stay deferred through coercion callbacks in
                // limited circumstances, when we know the listener is internal.
                // Since we never assign DeferredReference instances to
                // non-internal (non-friend assembly) classes, it's safe to skip 
                // the dereference if the callback is to the DP owner (and not
                // a derived type).  This is consistent with passing raw 
                // DeferredReference instances to ValidateValue callbacks, which 
                // only ever go to the owner class.
                if (!coerceWithDeferredReference || 
                    dp.OwnerType != metadata.CoerceValueCallback.Method.DeclaringType) // Need 2nd check to rule out derived class callback overrides.
                {
                    // Resolve deferred references because we need the actual
                    // baseValue to evaluate the correct animated value. This is done 
                    // by invoking GetValue for this property.
                    DeferredReference dr = (DeferredReference) baseValue; 
                    baseValue = dr.GetValue(newEntry.BaseValueSourceInternal); 

                    // Set the baseValue back into the entry 
                    newEntry.SetCoersionBaseValue(baseValue);

                    entryIndex = CheckEntryIndex(entryIndex, targetIndex);
                } 
            }
 
            object coercedValue = coerceWithCurrentValue ? controlValue : coerceValueCallback(this, baseValue); 

            // Make sure that the call out did not cause a change to entryIndex 
            entryIndex = CheckEntryIndex(entryIndex, targetIndex);

            // Even if we used the controlValue in the coerce callback, we still want to compare against the original baseValue
            // to determine if we need to set a coerced value. 
            if (!Equals(dp, coercedValue, baseValue))
            { 
                // returning DependencyProperty.UnsetValue from a Coercion callback means "don't do the set" ... 
                // or "use previous value"
                if (coercedValue == DependencyProperty.UnsetValue) 
                {
                    if (oldEntry.IsDeferredReference)
                    {
                        DeferredReference reference = (DeferredReference)oldValue; 
                        oldValue = reference.GetValue(oldEntry.BaseValueSourceInternal);
 
                        entryIndex = CheckEntryIndex(entryIndex, targetIndex); 
                    }
 
                    coercedValue = oldValue;
                }

                // Note that we do not support the value being coerced to a 
                // DeferredReference
                if (!dp.IsValidValue(coercedValue)) 
                { 
                    // well... unless it's the control's "current value"
                    if (!(coerceWithCurrentValue && coercedValue is DeferredReference)) 
                        throw new ArgumentException(SR.Get(SRID.InvalidPropertyValue, coercedValue, dp.Name));
                }

                // Set the coerced value here. All other values would 
                // have been set during EvaluateEffectiveValue/GetValueCore.
 
                newEntry.SetCoercedValue(coercedValue, baseValue, skipBaseValueChecks, coerceWithCurrentValue); 
            }
        } 
        /// <summary>
        ///     Simple value set on template child
        /// </summary>
        /// <param name="dp">Dependent property</param>
        /// <param name="value">Value to set</param>
        public void SetValue(DependencyProperty dp, object value)
        {
            if (_sealed)
            {
                throw new InvalidOperationException(SR.Get(SRID.CannotChangeAfterSealed, "FrameworkElementFactory"));
            }

            if (dp == null)
            {
                throw new ArgumentNullException("dp");
            }

            // Value needs to be valid for the DP, or Binding/MultiBinding/PriorityBinding.
            //  (They all have MarkupExtension, which we don't actually support, see above check.)

            if (!dp.IsValidValue(value) && !(value is MarkupExtension) && !(value is DeferredReference))
            {
                throw new ArgumentException(SR.Get(SRID.InvalidPropertyValue, value, dp.Name));
            }

            // Styling the logical tree is not supported
            if (StyleHelper.IsStylingLogicalTree(dp, value))
            {
                throw new NotSupportedException(SR.Get(SRID.ModifyingLogicalTreeViaStylesNotImplemented, value, "FrameworkElementFactory.SetValue"));
            }

            #pragma warning suppress 6506 // dp.DefaultMetadata is never null
            if (dp.ReadOnly)
            {
                // Read-only properties will not be consulting FrameworkElementFactory for value.
                //  Rather than silently do nothing, throw error.
                throw new ArgumentException(SR.Get(SRID.ReadOnlyPropertyNotAllowed, dp.Name, GetType().Name));
            }

            ResourceReferenceExpression resourceExpression = value as ResourceReferenceExpression;
            DynamicResourceExtension dynamicResourceExtension = value as DynamicResourceExtension;
            object resourceKey = null;

            if( resourceExpression != null )
            {
                resourceKey = resourceExpression.ResourceKey;
            }
            else if( dynamicResourceExtension != null )
            {
                resourceKey = dynamicResourceExtension.ResourceKey;
            }

            if (resourceKey == null)
            {
                TemplateBindingExtension templateBinding = value as TemplateBindingExtension;
                if (templateBinding == null)
                {
                    UpdatePropertyValueList( dp, PropertyValueType.Set, value );
                }
                else
                {
                    UpdatePropertyValueList( dp, PropertyValueType.TemplateBinding, templateBinding );
                }
            }
            else
            {
                UpdatePropertyValueList(dp, PropertyValueType.Resource, resourceKey);
            }
        }
예제 #16
0
        //
        //  This method
        //  1. Computes the property value given the ChildLookupValue list for it
        //
        private static object GetChildValueHelper(
            UncommonField<HybridDictionary[]>       dataField,
            ref ItemStructList<ChildValueLookup>    valueLookupList,
            DependencyProperty                      dp,
            DependencyObject                        container,
            FrameworkObject                         child,
            int                                     childIndex,
            bool                                    styleLookup,
            ref EffectiveValueEntry                 entry,
            out ValueLookupType                     sourceType,
            FrameworkElementFactory                 templateRoot)
        {
            Debug.Assert(child.IsValid, "child should either be an FE or an FCE");

            object value = DependencyProperty.UnsetValue;
            sourceType = ValueLookupType.Simple;

            // Walk list backwards since highest priority lookup items are inserted last
            for (int i = valueLookupList.Count - 1; i >= 0; i--)
            {
                sourceType = valueLookupList.List[i].LookupType;

                // Lookup logic is determined by lookup type. "Trigger"
                // is misleading right now because today it's also being used
                // for Storyboard timeline lookups.
                switch (valueLookupList.List[i].LookupType)
                {
                case ValueLookupType.Simple:
                    {
                        // Simple value
                        value = valueLookupList.List[i].Value;
                    }
                    break;

                case ValueLookupType.Trigger:
                case ValueLookupType.PropertyTriggerResource:
                case ValueLookupType.DataTrigger:
                case ValueLookupType.DataTriggerResource:
                    {
                        // Conditional value based on Container state
                        bool triggerMatch = true;

                        if( valueLookupList.List[i].Conditions != null )
                        {
                            // Check whether the trigger applies.  All conditions must match,
                            // so the loop can terminate as soon as it finds a condition
                            // that doesn't match.
                            for (int j = 0; triggerMatch && j < valueLookupList.List[i].Conditions.Length; j++)
                            {
                                object state;

                                switch (valueLookupList.List[i].LookupType)
                                {
                                case ValueLookupType.Trigger:
                                case ValueLookupType.PropertyTriggerResource:
                                    // Find the source node
                                    DependencyObject sourceNode;
                                    int sourceChildIndex = valueLookupList.List[i].Conditions[j].SourceChildIndex;
                                    if (sourceChildIndex == 0)
                                    {
                                        sourceNode = container;
                                    }
                                    else
                                    {
                                        sourceNode = StyleHelper.GetChild(container, sourceChildIndex);
                                    }

                                    // Note that the sourceNode could be null when the source
                                    // property for this trigger is on a node that hasn't been
                                    // instantiated yet.
                                    DependencyProperty sourceProperty = valueLookupList.List[i].Conditions[j].Property;
                                    if (sourceNode != null)
                                    {
                                        state = sourceNode.GetValue(sourceProperty);
                                    }
                                    else
                                    {
                                        Type sourceNodeType;

                                        if( templateRoot != null )
                                        {
                                            sourceNodeType = FindFEF(templateRoot, sourceChildIndex).Type;
                                        }
                                        else
                                        {
                                            sourceNodeType = (container as FrameworkElement).TemplateInternal.ChildTypeFromChildIndex[sourceChildIndex];
                                        }

                                        state = sourceProperty.GetDefaultValue(sourceNodeType);
                                    }

                                    triggerMatch = valueLookupList.List[i].Conditions[j].Match(state);

                                    break;

                                case ValueLookupType.DataTrigger:
                                case ValueLookupType.DataTriggerResource:
                                default:    // this cannot happen - but make the compiler happy

                                    state = GetDataTriggerValue(dataField, container, valueLookupList.List[i].Conditions[j].Binding);
                                    triggerMatch = valueLookupList.List[i].Conditions[j].ConvertAndMatch(state);

                                    break;
                                }
                            }
                        }

                        if (triggerMatch)
                        {
                            // Conditionals matched, use the value

                            if (valueLookupList.List[i].LookupType == ValueLookupType.PropertyTriggerResource ||
                                valueLookupList.List[i].LookupType == ValueLookupType.DataTriggerResource)
                            {
                                // Resource lookup
                                object source;
                                value = FrameworkElement.FindResourceInternal(child.FE,
                                                                              child.FCE,
                                                                              dp,
                                                                              valueLookupList.List[i].Value,  // resourceKey
                                                                              null,  // unlinkedParent
                                                                              true,  // allowDeferredResourceReference
                                                                              false, // mustReturnDeferredResourceReference
                                                                              null,  // boundaryElement
                                                                              false, // disableThrowOnResourceNotFound
                                                                              out source);

                                // Try to freeze the value
                                SealIfSealable(value);
                            }
                            else
                            {
                                value = valueLookupList.List[i].Value;
                            }
                        }
                    }
                    break;

                case ValueLookupType.TemplateBinding:
                    {
                        TemplateBindingExtension templateBinding = (TemplateBindingExtension)valueLookupList.List[i].Value;
                        DependencyProperty sourceProperty = templateBinding.Property;

                        // Direct binding of Child property to Container
                        value = container.GetValue(sourceProperty);

                        // Apply the converter, if any
                        if (templateBinding.Converter != null)
                        {
                            DependencyProperty targetProperty = valueLookupList.List[i].Property;
                            System.Globalization.CultureInfo culture = child.Language.GetCompatibleCulture();

                            value = templateBinding.Converter.Convert(
                                                value,
                                                targetProperty.PropertyType,
                                                templateBinding.ConverterParameter,
                                                culture);
                        }

                        // if the binding returns an invalid value, fallback to default value
                        if ((value != DependencyProperty.UnsetValue) && !dp.IsValidValue(value))
                        {
                            value = DependencyProperty.UnsetValue;
                        }
                    }
                    break;

                case ValueLookupType.Resource:
                    {
                        // Resource lookup
                        object source;
                        value = FrameworkElement.FindResourceInternal(
                                        child.FE,
                                        child.FCE,
                                        dp,
                                        valueLookupList.List[i].Value,  // resourceKey
                                        null,  // unlinkedParent
                                        true,  // allowDeferredResourceReference
                                        false, // mustReturnDeferredResourceReference
                                        null,  // boundaryElement
                                        false, // disableThrowOnResourceNotFound
                                        out source);

                        // Try to freeze the value
                        SealIfSealable(value);
                    }
                    break;
                }

                // See if value needs per-instance storage
                if (value != DependencyProperty.UnsetValue)
                {
                    entry.Value = value;
                    // When the value requires per-instance storage (and comes from this style),
                    // get the real value from per-instance data.
                    switch (valueLookupList.List[i].LookupType)
                    {
                    case ValueLookupType.Simple:
                    case ValueLookupType.Trigger:
                    case ValueLookupType.DataTrigger:
                        {
                            MarkupExtension me;
                            Freezable freezable;

                            if ((me = value as MarkupExtension) != null)
                            {
                                value = GetInstanceValue(
                                                dataField,
                                                container,
                                                child.FE,
                                                child.FCE,
                                                childIndex,
                                                valueLookupList.List[i].Property,
                                                i,
                                                ref entry);
                            }
                            else if ((freezable = value as Freezable) != null && !freezable.IsFrozen)
                            {
                                value = GetInstanceValue(
                                                dataField,
                                                container,
                                                child.FE,
                                                child.FCE,
                                                childIndex,
                                                valueLookupList.List[i].Property,
                                                i,
                                                ref entry);
                            }
                        }
                        break;

                    default:
                        break;
                    }
                }

                if (value != DependencyProperty.UnsetValue)
                {
                    // Found a value, break out of the for() loop.
                    break;
                }
            }

            return value;
        }
 private bool IsValueValid(object newValue)
 {
     return(newValue != ObservableValue.UnsetValue && dependencyProperty.IsValidValue(newValue));
 }
예제 #18
0
        /// <summary>Sets the value of a dependency property.</summary>
        /// <param name="dp">The dependency property identifier of the property to set.</param>
        /// <param name="value">The new value.</param>
        public void SetValue(DependencyProperty dp, object value)
        {
            if (this.@sealed)
            {
                throw new InvalidOperationException("Can't change FrameworkElementFactory after sealed");
            }
            if (dp == null)
            {
                throw new ArgumentNullException("dp");
            }
            if (!dp.IsValidValue(value) && !(value is MarkupExtension) && !(value is DeferredReference) && !(value is BindingBase))
            {
                object[] objArray1 = new object[] { value, dp.Name };
                throw new ArgumentException("InvalidPropertyValue");
            }

            /*
            //if (StyleHelper.IsStylingLogicalTree(dp, value))
            //{
            //    throw new NotSupportedException("ModifyingLogicalTreeViaStylesNotImplemented");
            //}
            */

            if (dp.ReadOnly)
            {
                throw new ArgumentException("ReadOnlyPropertyNotAllowed");
            }
            ResourceReferenceExpression resourceReferenceExpression = value as ResourceReferenceExpression;
            object resourceKey = null;
            if (resourceReferenceExpression != null)
            {
                resourceKey = resourceReferenceExpression.ResourceKey;
            }
            if (resourceKey != null)
            {
                this.UpdatePropertyValueList(dp, PropertyValueType.Resource, resourceKey);
                return;
            }
            TemplateBindingExtension templateBindingExtension = value as TemplateBindingExtension;
            if (templateBindingExtension != null)
            {
                this.UpdatePropertyValueList(dp, PropertyValueType.TemplateBinding, templateBindingExtension);
                return;
            }
            this.UpdatePropertyValueList(dp, PropertyValueType.Set, value);
        }
예제 #19
0
        private void SetValue(DependencyProperty dependencyProperty, DependencyPropertyKey dependencyPropertyKey, object value, BaseValueSource source)
        {
            VerifyReadOnlyProperty(dependencyProperty, dependencyPropertyKey);

            IExpressionProvider newExpressionProvider = value as IExpressionProvider;
            if (newExpressionProvider == null && !dependencyProperty.IsValidValue(value))
            {
                return;
            }

            IDependencyPropertyValueEntry entry = GetInitializedValueEntry(dependencyProperty);

            IExpression oldExpression = entry.GetBaseValue((int)source, false) as IExpression;

            if (newExpressionProvider != null)
            {
                value = newExpressionProvider.CreateExpression(this, dependencyProperty);
            }
            else if (oldExpression != null && oldExpression.SetValue(value))
            {
                return;
            }

            if (oldExpression is IDisposable)
            {
                ((IDisposable)oldExpression).Dispose();
            }

            entry.SetBaseValue((int)source, value);
        }
예제 #20
0
        private void SetValue(DependencyProperty dependencyProperty, DependencyPropertyKey dependencyPropertyKey, object value, bool setCurrentValue = false, BaseValueSource source = BaseValueSource.Unknown)
        {
            VerifyReadOnlyProperty(dependencyProperty, dependencyPropertyKey);

            IExpressionProvider newExpressionProvider = value as IExpressionProvider;
            if (newExpressionProvider == null && !dependencyProperty.IsValidValue(value))
            {
                return; // invalid value
            }

            IDependencyPropertyValueEntry entry = GetInitializedValueEntry(dependencyProperty);

            IExpression oldExpression = setCurrentValue ?
                entry.GetBaseValue(false) as IExpression : // current value may be set in the top priority expression
                entry.GetBaseValue((int)source, false) as IExpression;

            if (newExpressionProvider != null)
            {
                value = newExpressionProvider.CreateExpression(this, dependencyProperty);
            }
            else if (oldExpression != null && oldExpression.SetValue(value))
            {
                return; // value (current or not) was set in the existing expression, nothing else to do
            }

            if (setCurrentValue)
            {
                entry.SetCurrentValue(value);
                return; // base value isn't changed
            }

            if (oldExpression is IDisposable) // expression is being replaced
            {
                ((IDisposable)oldExpression).Dispose();
            }

            entry.SetBaseValue((int)source, value);
            entry.ClearCurrentValue();
        }
        /// <summary>Sets the value of a dependency property.</summary>
        /// <param name="dp">The dependency property identifier of the property to set.</param>
        /// <param name="value">The new value.</param>
        // Token: 0x0600067D RID: 1661 RVA: 0x00014260 File Offset: 0x00012460
        public void SetValue(DependencyProperty dp, object value)
        {
            if (this._sealed)
            {
                throw new InvalidOperationException(SR.Get("CannotChangeAfterSealed", new object[]
                {
                    "FrameworkElementFactory"
                }));
            }
            if (dp == null)
            {
                throw new ArgumentNullException("dp");
            }
            if (!dp.IsValidValue(value) && !(value is MarkupExtension) && !(value is DeferredReference))
            {
                throw new ArgumentException(SR.Get("InvalidPropertyValue", new object[]
                {
                    value,
                    dp.Name
                }));
            }
            if (StyleHelper.IsStylingLogicalTree(dp, value))
            {
                throw new NotSupportedException(SR.Get("ModifyingLogicalTreeViaStylesNotImplemented", new object[]
                {
                    value,
                    "FrameworkElementFactory.SetValue"
                }));
            }
            if (dp.ReadOnly)
            {
                throw new ArgumentException(SR.Get("ReadOnlyPropertyNotAllowed", new object[]
                {
                    dp.Name,
                    base.GetType().Name
                }));
            }
            ResourceReferenceExpression resourceReferenceExpression = value as ResourceReferenceExpression;
            DynamicResourceExtension    dynamicResourceExtension    = value as DynamicResourceExtension;
            object obj = null;

            if (resourceReferenceExpression != null)
            {
                obj = resourceReferenceExpression.ResourceKey;
            }
            else if (dynamicResourceExtension != null)
            {
                obj = dynamicResourceExtension.ResourceKey;
            }
            if (obj != null)
            {
                this.UpdatePropertyValueList(dp, PropertyValueType.Resource, obj);
                return;
            }
            TemplateBindingExtension templateBindingExtension = value as TemplateBindingExtension;

            if (templateBindingExtension == null)
            {
                this.UpdatePropertyValueList(dp, PropertyValueType.Set, value);
                return;
            }
            this.UpdatePropertyValueList(dp, PropertyValueType.TemplateBinding, templateBindingExtension);
        }