示例#1
0
        public static object GetValue(BindingExpression expression)
        {
            Type currentType = null;
            if (expression == null)
            {
                return null;
            }
            object dataItem = expression.DataItem;
            if (dataItem == null)
            {
                return null;
            }
            string bindingPath = expression.ParentBinding.Path.Path;
            string[] properties = bindingPath.Split('.');

            object currentObject = dataItem;
            for (int i = 0; i < properties.Length; i++)
            {
                currentType = currentObject.GetType();
                PropertyInfo property = currentType.GetProperty(properties[i]);
                if (property == null)
                {
                    currentObject = null;
                    break;
                }
                currentObject = property.GetValue(currentObject, null);
                if (currentObject == null)
                {
                    break;
                }
            }

            return currentObject;
        }
示例#2
0
 private static void RefreshBindingExpression(BindingExpression bindingExpression)
 {
     if (bindingExpression != null)
     {
         bindingExpression.UpdateSource();
     }
 }
示例#3
0
        static object GetContext(System.Windows.Data.BindingExpression binding, out string propertyName)
        {
            var context = binding.DataItem;

            var allPathes = binding.ParentBinding.Path.Path.Split('.');

            propertyName = "";
            int i = 1;

            foreach (var path in allPathes)
            {
                propertyName = path;
                if (i != allPathes.Length)
                {
                    if (context != null)
                    {
                        var property = context.GetType().GetProperty(path);
                        if (property == null)
                        {
                            throw new Exception($"{path} does not exist on {context.GetType().FullName}");
                        }
                        context = property.GetValue(context, null);
                    }
                }
                i++;
            }
            return(context);
        }
        /// <summary>
        /// Parse metadata from a target FrameworkElement.  This will cache the metadata on the element as an attached property.
        /// </summary>
        /// <param name="element">The target FrameworkElement to pull metadata from.</param>
        /// <param name="forceUpdate">If set, will not pull metadata from cache.</param>
        /// <param name="entity">The entity used.</param>
        /// <param name="bindingExpression">The bindingExpression used.</param>
        /// <returns>Returns the metadata associated with the element.  Will be null if no metadata was found.</returns>
        internal static ValidationMetadata ParseMetadata(FrameworkElement element, bool forceUpdate, out object entity, out BindingExpression bindingExpression)
        {
            entity = null;
            bindingExpression = null;
            if (element == null)
            {
                return null;
            }

            if (!forceUpdate)
            {
                ValidationMetadata existingVMD = element.GetValue(ValidationMetadataProperty) as ValidationMetadata;
                if (existingVMD != null)
                {
                    return existingVMD;
                }
            }

            BindingExpression be = null;
            FieldInfo[] fields = element.GetType().GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy);
            foreach (FieldInfo field in fields)
            {
                if (field.FieldType == typeof(DependencyProperty))
                {
                    // Found a dependency property
                    be = element.GetBindingExpression((DependencyProperty)field.GetValue(null));
                    if (be != null && be.ParentBinding != null && be.ParentBinding.Path != null)
                    {
                        // Found a BindingExpression, ensure it has valid data
                        entity = be.DataItem != null ? be.DataItem : element.DataContext;
                        if (entity != null)
                        {
                            if (be.ParentBinding.Mode == BindingMode.TwoWay)
                            {
                                bindingExpression = be;
                                // A twoway binding will be automatically chosen and the rest ignored
                                break;
                            }

                            // Perform an arbitrary sort on path (string), so the same dependency property is chosen consistently.
                            // Reflection ordering is not deterministic and if we just pick the first, we could be
                            // matched with different dependency properties depending on the run.
                            if (bindingExpression == null || string.Compare(be.ParentBinding.Path.Path, bindingExpression.ParentBinding.Path.Path, StringComparison.Ordinal) < 0)
                            {
                                bindingExpression = be;
                            }
                        }
                    }
                }
            }
            if (bindingExpression != null)
            {
                ValidationMetadata newVMD = ParseMetadata(bindingExpression.ParentBinding.Path.Path, entity);
                element.SetValue(ValidationMetadataProperty, newVMD);
                return newVMD;
            }
            return null;
        }
示例#5
0
 private void _selectionChanged(Object sender, SelectionChangedEventArgs e) {
   if (this._bE == null) {
     this._bE = this.GetBindingExpression(SelectedValueProperty);
   } else {
     if (this.GetBindingExpression(SelectedValueProperty) == null) {
       this.SetBinding(SelectedValueProperty, this._bE.ParentBinding);
     }
   }
 }
 public static string GetTargetValue(BindingExpression expression)
 {
     Binding binding = CloneBinding(expression.ParentBinding, expression.DataItem);
     binding.Mode = BindingMode.OneTime;
     Dummy _dummy = new Dummy();
     BindingOperations.SetBinding(_dummy, Dummy.TextProperty, binding);
     BindingExpression newExpression = BindingOperations.GetBindingExpression(_dummy, Dummy.TextProperty);
     string text = _dummy.GetValue(Dummy.TextProperty) as string;
     return text;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="ValidatorRule"/> class for a binding expression.
        /// </summary>
        /// <param name="bindingExpression">The expression to validate.</param>
        public ValidatorRule(BindingExpression bindingExpression)
            : base(ValidationStep.ConvertedProposedValue, false)
        {
            if (bindingExpression == null)
            {
                throw new ArgumentNullException("bindingExpression");
            }

            this.bindingExpression = bindingExpression;
        }
        public EditEventProperty()
        {
            InitializeComponent();
            _appb = new EditPageSaveEditButton(this.ApplicationBar, VM);
            _delete = new EditPageDeleteButton(ApplicationBar, VM);

            _filterBinding = tbFilterString.GetBindingExpression(TextBox.TextProperty);

            Observable.FromEventPattern(tbFilterString, "TextChanged")
                .Subscribe(_ => _filterBinding.UpdateSource());
        }
        public static TestValidationError GetFor(BindingExpression expression)
        {
            var source = (UIElement)expression.ParentBinding.Source;
            var match = Cache.SingleOrDefault(x => ReferenceEquals(x.Item1, source));
            if (match != null)
            {
                return match.Item2;
            }

            var error = new TestValidationError(expression.ParentBinding);
            Cache.Add(Tuple.Create(source, error));

            return error;
        }
示例#10
0
        public Control()
        {
            InitializeComponent();

            ServiceController.Communicator.ConfigureDatabaseStepsOnChanged += Communicator_ConfigureDatabaseStepsOnChanged;

            DataContext = data;

            userNameTextBoxBinding = userNameTextBox.GetBindingExpression(TextBox.TextProperty);
            passwordBoxBinding = passwordBox.GetBindingExpression(PasswordBoxExtension.PasswordProperty);
            confirmPasswordBoxBinding = confirmPasswordBox.GetBindingExpression(PasswordBoxExtension.PasswordProperty);
            serverIpAddressTextBoxBinding = serverIpAddressTextBox.GetBindingExpression(TextBox.TextProperty);

            serverConfigurationGrid.DataContext = Communicator.ServiceController.Communicator.ActiveServer;
        }
示例#11
0
        private void SetImmediate(DependencyObject target)
        {
            _target = target;
            _bindingExpression = BindingOperations.GetBindingExpression(target, _property);
            if (_bindingExpression == null)
                throw new InvalidOperationException("Binding not found on " + target + " " + _property.Name + ".");

            if (_bindingExpression.ParentBinding.UpdateSourceTrigger != UpdateSourceTrigger.Explicit)
                throw new InvalidOperationException("Binding UpdateSourceTrigger must be set to Explicit.");

            var descriptor = DependencyPropertyDescriptor.FromProperty(_property, target.GetType());
            descriptor.AddValueChanged(target, (sender, e) => {
                _timer.Stop();
                _timer.Start();
            });
        }
示例#12
0
        static DispatcherTimer BuildTimer(object control, BindingExpression exp, int milliseconds)
        {
            var timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(milliseconds);
            timer.Tick += (sender, e) =>
            {
                exp.UpdateSource();

                lock (Timers)
                {
                    timer.Stop();
                    Timers.Remove(control);
                }
            };
            return timer;
        }
        private void UpdateBindings()
        {
            BindingExpression[] expressions = new BindingExpression[]
            {
                rbPlayer1ControlHuman.GetBindingExpression(RadioButton.IsCheckedProperty),
                rbPlayer1ControlComputer.GetBindingExpression(RadioButton.IsCheckedProperty),
                rbPlayer1DifficultyEasy.GetBindingExpression(RadioButton.IsCheckedProperty),
                rbPlayer1DifficultyNormal.GetBindingExpression(RadioButton.IsCheckedProperty),
                rbPlayer1DifficultyHard.GetBindingExpression(RadioButton.IsCheckedProperty),
                rbPlayer2ControlHuman.GetBindingExpression(RadioButton.IsCheckedProperty),
                rbPlayer2ControlComputer.GetBindingExpression(RadioButton.IsCheckedProperty),
                rbPlayer2DifficultyEasy.GetBindingExpression(RadioButton.IsCheckedProperty),
                rbPlayer2DifficultyNormal.GetBindingExpression(RadioButton.IsCheckedProperty),
                rbPlayer2DifficultyHard.GetBindingExpression(RadioButton.IsCheckedProperty)
            };

            foreach (var ex in expressions) ex.UpdateSource();
        }
示例#14
0
		public static BindingExpressionBase SetBinding (DependencyObject target, DependencyProperty dp, BindingBase binding)
		{
			if (target == null)
				throw new ArgumentNullException ("target");
			if (dp == null)
				throw new ArgumentNullException ("dp");
			if (binding == null)
				throw new ArgumentNullException ("binding");


			if (dp == null)
				throw new ArgumentNullException ("dp");
			if (binding == null)
				throw new ArgumentNullException ("binding");

			BindingExpression e = new BindingExpression ((Binding) binding, target, dp);
			target.SetValue (dp, e);
			return e;
		}
 public IFilter GetFilter(BindingExpression be, DataGrid dg)
 {
     Type t = be.ResolvedSource.GetType();
     String typeName = t.GetProperty(be.ResolvedSourcePropertyName).GetValue(be.ResolvedSource).GetType().ToString();
     IFilter filter= null;
     switch (typeName)
     {
         case "int":
             break;
         case "string":
             break;
         case "DateTime":
             break;
         default:
             filter = new TextFilter();
             break;
     }
     filter.Fill(be, dg);
     return filter;
 }
示例#16
0
        internal static LabelValidationMetadata ParseMetadata(FrameworkElement element, bool forceUpdate, out object entity, out BindingExpression bindingExpression)
        {
            entity = (object)null;
            bindingExpression = (BindingExpression)null;
            if (element == null)
                return (LabelValidationMetadata)null;
            if (!forceUpdate)
            {
                LabelValidationMetadata validationMetadata = element.GetValue(LabelValidationHelper.ValidationMetadataProperty) as LabelValidationMetadata;
                if (validationMetadata != null)
                    return validationMetadata;
            }
            foreach (FieldInfo fieldInfo in element.GetType().GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy))
            {
                if (fieldInfo.FieldType == typeof(DependencyProperty))
                {
                    BindingExpression bindingExpression1 = element.GetBindingExpression((DependencyProperty)fieldInfo.GetValue((object)null));
                    if (bindingExpression1 != null && bindingExpression1.ParentBinding != null && bindingExpression1.ParentBinding.Path != null)
                    {
                        entity = bindingExpression1.DataItem ?? element.DataContext;
                        if (entity != null)
                        {
                            if (bindingExpression1.ParentBinding.Mode == BindingMode.TwoWay)
                            {
                                bindingExpression = bindingExpression1;
                                break;
                            }
                            else if (bindingExpression == null || string.Compare(bindingExpression1.ParentBinding.Path.Path, bindingExpression.ParentBinding.Path.Path, StringComparison.Ordinal) < 0)
                                bindingExpression = bindingExpression1;
                        }
                    }
                }
            }

            if (bindingExpression == null)
                return null;

            LabelValidationMetadata validationMetadata1 = ParseMetadata(bindingExpression.ParentBinding.Path.Path, entity);
            element.SetValue(ValidationMetadataProperty, (object)validationMetadata1);
            return validationMetadata1;
        }
示例#17
0
        //-----------------------------------------------------
        // 
        //  Constructors 
        //
        //----------------------------------------------------- 

        internal ClrBindingWorker(BindingExpression b, DataBindEngine engine) : base(b)
        {
            PropertyPath path = ParentBinding.Path; 

            if (ParentBinding.XPath != null) 
            { 
                path = PrepareXmlBinding(path);
            } 

            if (path == null)
            {
                path = new PropertyPath(String.Empty); 
            }
 
            if (ParentBinding.Path == null) 
            {
                ParentBinding.UsePath(path); 
            }

            _pathWorker = new PropertyPathWorker(path, this, IsDynamic, engine);
            _pathWorker.SetTreeContext(ParentBindingExpression.TargetElementReference); 
        }
示例#18
0
 private void OnEnterNewEarningsKeyDown(object sender, KeyEventArgs e)
 {
     if (e.Key == Key.Return)
     {
         if (_bindingExpression != null)
         {
             _bindingExpression.UpdateSource();
         }
         else
         {
             TextBox tb = sender as TextBox;
             if (tb != null)
             {
                 _bindingExpression = BindingOperations.GetBindingExpression(tb, TextBox.TextProperty);
                 if (_bindingExpression != null)
                 {
                     _bindingExpression.UpdateSource();
                 }
             }
         }
     }
 }
        public void Fill(BindingExpression be, DataGrid dg)
        {
            
            Type t = be.ResolvedSource.GetType();
            List<string> str = new List<string>();
            foreach (var obj in dg.Items)
            {
                if (obj.GetType().ToString().Contains("People"))
                    str.Add(t.GetProperty(be.ResolvedSourcePropertyName).GetValue(obj).ToString());
            }
            var colect = from strin in str group strin by strin into newGroup select newGroup;

            FilterCollection = new List<ItemFilter>();

            foreach (IGrouping<string, string> obj in colect)
            {
                FilterCollection.Add(new ItemFilter() { Name = obj.Key, IsCheked = true });
            }
            FilterCollection.Sort((a,b)=>a.Name.CompareTo(b.Name));

            col.Source = FilterCollection;
            Header = be.ResolvedSourcePropertyName;

        }
 internal ChangingValueHelper(BindingExpression b)
 {
     _bindingExpression = b;
     b.CancelPendingTasks();
 }
 protected BindingWorker(BindingExpression b)
 {
     _bindingExpression = b;
 }
示例#22
0
        // check if source needs to be updated
        private bool HasDifferentValue(BindingExpression b)
        {
            var originObj = b.ResolvedSource;
            var propName = b.ResolvedSourcePropertyName;

            var originValue = originObj.GetType().GetProperty(propName).GetValue(originObj);
            var currentValue = b.Target.GetValue(b.TargetProperty);
            return originValue != currentValue;
        }
示例#23
0
 internal ProposedValue(BindingExpression bindingExpression, object rawValue, object convertedValue) 
 {
     _bindingExpression = bindingExpression; 
     _rawValue = rawValue; 
     _convertedValue = convertedValue;
 } 
        internal static string GetCheckedPath(BindingExpression bindingExpression)
        {
            var pathText = bindingExpression.ParentBinding.Path.Path;

            if (!pathValidationRegex.IsMatch(pathText))
            {
                throw new InvalidOperationException(
                    string.Format(
                        CultureInfo.CurrentCulture,
                        Resources.ExceptionComplexBindingPath,
                        pathText));
            }

            return pathText;
        }
 /// <summary>
 /// Creates a new BindingInfo with the specified BindingExpression, BindingTarget and Element.
 /// </summary>
 /// <param name="bindingExpression">BindingExpression</param>
 /// <param name="bindingTarget">BindingTarget</param>
 /// <param name="element">Element</param>
 public BindingInfo(BindingExpression bindingExpression, DependencyProperty bindingTarget, FrameworkElement element)
 {
     this.BindingExpression = bindingExpression;
     this.BindingTarget = bindingTarget;
     this.Element = element;
 }
示例#26
0
        /// <summary>
        /// Overridden. Applies the specified template.
        /// </summary>
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            this.VerticalScrollBar = this.GetTemplateChild<ScrollBar>(VerticalScrollBarElementName, true);
            this.NonDynamicRightAxisViewPort = this.GetTemplateChild<Canvas>(NonDynamicRightAxisViewPortElementName, true);
            this.futureCanvas = this.GetTemplateChild<FrameworkElement>(FutureCanvasElementName, false);
           
            if (this.PointTemplate == null)
            {
                this.PointTemplate = StyleParser.FindResource<DataTemplate>(this.LayoutRoot, DataPointTemplateResourceKey, true);
            }

            if (this.LabelTemplate == null)
            {
                this.LabelTemplate = StyleParser.FindResource<DataTemplate>(this.LayoutRoot, DataPointLabelTemplateResourceKey, false);
            }

            if (this.LabelTransform == null)
            {
                this.LabelTransform = StyleParser.FindResource<Transform>(this.LayoutRoot, DataPointLabelTransformResourceKey, false);
            }

            this.xaxisLabelTemplate = StyleParser.FindResource<DataTemplate>(this.LayoutRoot, XAxisLabelTemplateElementName, true);

#if !SILVERLIGHT
            DependencyObject dp = this.PointTemplate.LoadContent();
            if (null != dp)
            {
                GraphPoint gp = dp as GraphPoint;
                if (null != gp)
                {
                    this.bindingY1 = gp.GetBindingExpression(GraphPoint.Y1Property);
                    this.bindingY2 = gp.GetBindingExpression(GraphPoint.Y2Property);
                    this.bindingX1 = gp.GetBindingExpression(GraphPoint.X1Property);
                    this.bindingX2 = gp.GetBindingExpression(GraphPoint.X2Property);
                    this.bindingDataMarkerTemplate = gp.GetBindingExpression(GraphPoint.DataMarkerTemplateProperty);
                    this.bindingLabel = gp.GetBindingExpression(GraphPoint.LabelProperty);
                }
            }
#endif
            // define the base zindex for the label
            FrameworkElement labelElement = null;
            if (null != this.LabelTemplate)
            {
                labelElement = this.LabelTemplate.LoadContent() as FrameworkElement;
                this.labelTemplateZindex = Canvas.GetZIndex(labelElement);
            }
        }
 private ErrorNode(BindingExpression errorCountExpression)
     : base(Validation.GetHasError((DependencyObject)errorCountExpression.ParentBinding.Source))
 {
     this.errorCountExpression = errorCountExpression;
     this.OnHasErrorsChanged();
 }
 public BindingValidatorItem(Control control, DependencyProperty dependencyProperty, string ErrorMessage)
 {
     this.m_Control = control;
     this.m_BindingExpression = this.m_Control.GetBindingExpression(dependencyProperty);
     this.m_ErrorMessage = ErrorMessage;
 }
示例#29
0
        //------------------------------------------------------
        //
        //  Protected Methods
        //
        //------------------------------------------------------

        /// <summary>
        /// Create an appropriate expression for this Binding, to be attached
        /// to the given DependencyProperty on the given DependencyObject.
        /// </summary>
        internal override BindingExpressionBase CreateBindingExpressionOverride(DependencyObject target, DependencyProperty dp, BindingExpressionBase owner)
        {
            return(BindingExpression.CreateBindingExpression(target, dp, this, owner));
        }
        //------------------------------------------------------
        //
        //  Internal Methods
        //
        //------------------------------------------------------

        // Create a new BindingExpression from the given Bind description
        internal static BindingExpression CreateBindingExpression(DependencyObject d,
                                                DependencyProperty dp,
                                                Binding binding,
                                                BindingExpressionBase parent)
        {
            FrameworkPropertyMetadata fwMetaData = dp.GetMetadata(d.DependencyObjectType) as FrameworkPropertyMetadata;

            if ((fwMetaData != null && !fwMetaData.IsDataBindingAllowed) || dp.ReadOnly)
                throw new ArgumentException(SR.Get(SRID.PropertyNotBindable, dp.Name), "dp");

            // create the BindingExpression
            BindingExpression bindExpr = new BindingExpression(binding, parent);

            bindExpr.ResolvePropertyDefaultSettings(binding.Mode, binding.UpdateSourceTrigger, fwMetaData);

            // Two-way Binding with an empty path makes no sense
            if (bindExpr.IsReflective && binding.XPath == null &&
                    (binding.Path == null || String.IsNullOrEmpty(binding.Path.Path)))
                throw new InvalidOperationException(SR.Get(SRID.TwoWayBindingNeedsPath));

            return bindExpr;
        }
示例#31
0
 private static Type GetBoundType(BindingExpression bindingExpression)
 {
     var split = bindingExpression.ParentBinding.Path.Path.Split('.').LastOrDefault();
     if (split == null)
         return null;
     var dataItem = bindingExpression.DataItem;
     if (dataItem == null)
         return null;
     var type = dataItem.GetType();
     var propertyInfo = type.GetProperty(split);
     if (propertyInfo == null)
         return null;
     return propertyInfo.PropertyType;
 }
示例#32
0
    /// <summary>
    /// Sets the binding values for this instance.
    /// </summary>
    private void SetBindingValues(BindingExpression binding)
    {
      var bindingPath = string.Empty;

      if (binding != null)
      {
        if (binding.ParentBinding != null && binding.ParentBinding.Path != null)
          bindingPath = binding.ParentBinding.Path.Path;
        else
          bindingPath = string.Empty;
      }

      BindingPath = bindingPath;
    }