public static void EnsureDataBindingUpToDateOnMembers(DependencyObject dpObject)
 {
     IList<DependencyProperty> list = null;
     if (!DependenciesPropertyCache.TryGetValue(dpObject.GetType(), out list))
     {
         list = new List<DependencyProperty>();
         for (Type type = dpObject.GetType(); type != null; type = type.GetTypeInfo().BaseType)
         {
             foreach (FieldInfo info in type.GetRuntimeFields())
             {
                 if (info.IsPublic && (info.FieldType == typeof(DependencyProperty)))
                 {
                     DependencyProperty item = info.GetValue(null) as DependencyProperty;
                     if (item != null)
                     {
                         list.Add(item);
                     }
                 }
             }
         }
         DependenciesPropertyCache[dpObject.GetType()] = list;
     }
     if (list != null)
     {
         foreach (DependencyProperty property2 in list)
         {
             EnsureBindingUpToDate(dpObject, property2);
         }
     }
 }
Example #2
0
        /// <summary>
        /// Attaches to the specified object.
        /// </summary>
        /// <param name="dependencyObject">
        /// The object to attach to.
        /// </param>
        /// <exception cref="InvalidOperationException">
        /// The Behavior is already hosted on a different element.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// dependencyObject does not satisfy the Behavior type constraint.
        /// </exception>
        public void Attach(DependencyObject dependencyObject)
        {
            if (this.AssociatedObject != null)
            {
                throw new InvalidOperationException("The Behavior is already hosted on a different element.");
            }

            _associatedObject = dependencyObject;

            if (dependencyObject != null)
            {
                if (!this.AssociatedType.GetTypeInfo().IsAssignableFrom(dependencyObject.GetType().GetTypeInfo()))
                {
                    throw new InvalidOperationException("dependencyObject does not satisfy the Behavior type constraint.");
                }

                var frameworkElement = this.AssociatedObject as FrameworkElement;

                if (frameworkElement != null)
                {
                    frameworkElement.Loaded += AssociatedFrameworkElementLoaded;
                    frameworkElement.Unloaded += AssociatedFrameworkElementUnloaded;
                }

                OnAttached();
            }
        } 
 private static DelayedRegionCreationBehavior GetBehavior(DependencyObject control, MockRegionManagerAccessor accessor, MockRegionAdapter adapter)
 {
     var mappings = new RegionAdapterMappings();
     mappings.RegisterMapping(control.GetType(), adapter);
     var behavior = new DelayedRegionCreationBehavior(mappings) { RegionManagerAccessor = accessor, TargetElement = control };
     return behavior;
 }
        private void AssertAttachArgument(DependencyObject associatedObject)
        {
            if (this.AssociatedObject != null)
            {
                throw new InvalidOperationException("multiple time associate.");
            }

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

            if (!this.AssociatedType.GetTypeInfo().IsAssignableFrom(associatedObject.GetType().GetTypeInfo()))
            {
                throw new ArgumentException(string.Format("{0} can't assign {1}",
                    associatedObject.GetType().FullName,
                    this.AssociatedType.FullName));
            }
        }
 public void Attach(DependencyObject obj)
 {
     AssociatedObject = obj;
     var evt = AssociatedObject.GetType().GetRuntimeEvent(Event);
     if (evt != null)
     {
         Observable.FromEventPattern<RoutedEventArgs>(AssociatedObject, Event)
           .Subscribe(se => FireCommand(se.EventArgs));
     }
 }
Example #6
0
 internal override void ApplyTo(DependencyObject o)
 {
     if (!(o is T))
     {
         this.Log().Error($"The provided instance [{o?.GetType()}] does not match the setter's target type [{typeof(T)}]");
     }
     else
     {
         Action?.Invoke((T)o);
     }
 }
        protected override Style SelectStyleCore(object item, DependencyObject container)
        {
            SolidColorBrush highlight;
            if (_index % 2 == 0)
                highlight = new SolidColorBrush(Colors.White);
            else
                highlight = new SolidColorBrush(Colors.CornflowerBlue);

            _index++;
            Style style = new Style(container.GetType());
            style.Setters.Add(new Setter(Control.BackgroundProperty, highlight));
            return style;
        }
Example #8
0
        private void DumpVisualTree(DependencyObject parent, ref List<DependencyObject> objects)
        {
            string typeName = parent.GetType().Name;
            string name = (string)(parent.GetValue(FrameworkElement.NameProperty) ?? "");
            
            if (parent == null) return;

            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(parent, i);
                objects.Add(child);
                DumpVisualTree(child, ref objects);
            }
        }
Example #9
0
 public void Attach(DependencyObject dependencyObject)
 {
     Type t = dependencyObject.GetType();
     string name = this.EventName;
     var eventinfo = t.GetRuntimeEvent(name);
     if (string.IsNullOrEmpty(name))
         throw new ArgumentException("请指定事件名称");
     if (eventinfo == null)
         throw new ArgumentException("指定需要动态添加的事件不存在");
     var executemethodinfo = this.GetType().GetTypeInfo().GetDeclaredMethod("Invok").CreateDelegate(eventinfo.EventHandlerType, this);
     WindowsRuntimeMarshal.AddEventHandler(
          del => (EventRegistrationToken)eventinfo.AddMethod.Invoke(dependencyObject, new object[] { del }),
         token => eventinfo.RemoveMethod.Invoke(dependencyObject, new object[] { token }), executemethodinfo);
     this.associatedObject = dependencyObject;
 }
Example #10
0
        private static void OnRoutedEventChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            string routedEvent = (string)e.NewValue;

            if (!string.IsNullOrEmpty(routedEvent))
            {
                EventHooker eventHooker = new EventHooker();
                eventHooker.ControlCommandObject = d;
                EventInfo eventInfo = GetEventInfo(d.GetType(), routedEvent);

                if (eventInfo != null)
                {
                    eventInfo.AddEventHandler(d, eventHooker.GetEventHandler(eventInfo));
                    //System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable<RoutedEventArgs>
                    //Info: http://www.microsoft.com/en-us/download/details.aspx?id=29058
                    //var eventpattern = System.Reactive.Linq.Observable.FromEventPattern<RoutedEventArgs>(d, routedEvent);
                }

            }
        }
        /// <summary>
        /// Registers a notification function for listening to changes to a tree of DependencyProperties relative to this DependencyObject instance.
        /// </summary>
        /// <param name="instance">The DependencyObject instance the dependency property tree starts at.</param>
        /// <param name="callback">A callback based on the PropertyChangedCallback delegate, which the system invokes when the value of any of the specified properties changes.</param>
        /// <param name="properties">The tree of dependency property to register for property-changed notification.</param>
        /// <returns>A disposable that will unregister the callback when disposed.</returns>
        /// <remarks>
        /// <para>Each node of the dependency property tree is represented by an array describing the path of the dependency property relative to the given dependency object instance.</para>
        /// <para>For example, to register for notifications to changes to the Color of a TextBlock's Foreground:</para>
        /// <code>var disposable = myTextBlock.RegisterDisposableNestedPropertyChangedCallback(callback, new [] { TextBlock.ForegroundProperty, SolidColorBrush.ColorProperty });</code>
        /// </remarks>
        internal static IDisposable RegisterDisposableNestedPropertyChangedCallback(this DependencyObject instance, PropertyChangedCallback callback, params DependencyProperty[][] properties)
        {
            if (instance == null)
            {
                return(Disposable.Empty);
            }

            return(properties
                   .Where(Enumerable.Any)
                   .GroupBy(Enumerable.First, propertyPath => propertyPath.Skip(1).ToArray())
                   .Where(Enumerable.Any)
                   .Where(group => group.Key != null)
                   .Select(group =>
            {
                var property = group.Key;
                var subProperties = group.ToArray();

                // Validate the property owner type
                if (!instance.GetType().Is(property.OwnerType) && !property.IsAttached)
                {
                    return Disposable.Empty;
                }

                var childDisposable = new SerialDisposable();

                childDisposable.Disposable = (instance.GetValue(property) as DependencyObject)?.RegisterDisposableNestedPropertyChangedCallback(callback, subProperties);

                var disposable = instance.RegisterDisposablePropertyChangedCallback(property, (s, e) =>
                {
                    callback(s, e);

                    childDisposable.Disposable = s?.RegisterDisposableNestedPropertyChangedCallback(callback, subProperties);
                });

                return new CompositeDisposable(disposable, childDisposable);
            })
                   .Apply(disposables => new CompositeDisposable(disposables)));
        }
Example #12
0
		public void Attach(DependencyObject dependencyObject)
		{
			if (this.AssociatedObject != dependencyObject)
			{
				if (this.AssociatedObject != null)
				{
					// TODO: message
					throw new InvalidOperationException();
				}

				if (dependencyObject == null) throw new ArgumentNullException(nameof(dependencyObject));
				if (!this.AssociatedType.GetTypeInfo().IsAssignableFrom(dependencyObject.GetType().GetTypeInfo()))
				{
					// TODO: message
					throw new InvalidOperationException();
				}

				this._associatedObject = dependencyObject;
				this.RaiseAssociatedObjectChanged();

				this.OnAttached();
			}
		}
        /// <summary>
        /// Traces the dependency object.
        /// </summary>
        /// <param name="dob">
        /// The dependancy object.
        /// </param>
        /// <param name="i">
        /// The object index.
        /// </param>
        private static void TraceDependencyObject(DependencyObject dob, int i)
        {
            var frameworkElement = dob as FrameworkElement;

            if (frameworkElement == null)
            {
                Debug.WriteLine(
                    "path[{0}] is Dependency Object: {1}",
                    i,
                    dob.GetType());
            }
            else
            {
                var c = frameworkElement as Control;
                var cc = frameworkElement as ContentControl;
                var panel = frameworkElement as Panel;
                var parentGrid = frameworkElement.Parent as Grid;
                var image = frameworkElement as Image;
                var scrollViewer = frameworkElement as ScrollViewer;

                Debug.WriteLine(
                    "path[{0}] is Control: {1}({2}):",
                    i,
                    frameworkElement.GetType(),
                    frameworkElement.Name ?? "<unnamed>");

                // Actual layout information
                Debug.WriteLine(
                    "\tActualWidth={0}\r\n\tActualHeight={1}",
                    frameworkElement.ActualWidth,
                    frameworkElement.ActualHeight);
                var pos =
                    frameworkElement
                        .TransformToVisual(Window.Current.Content)
                        .TransformPoint(new Point());
                var pos2 =
                    frameworkElement
                        .TransformToVisual(Window.Current.Content)
                        .TransformPoint(
                            new Point(
                                frameworkElement.ActualWidth,
                                frameworkElement.ActualHeight));

                Debug.WriteLine(
                    "\tPosition – X={0}, Y={1}, Right={2}, Bottom={3}",
                    pos.X,
                    pos.Y,
                    pos2.X,
                    pos2.Y);

                if (frameworkElement.Opacity < 1.0)
                {
                    Debug.WriteLine("\tOpacity={0}", frameworkElement.Opacity);
                }

                // DataContext often turns out to be a surprise
                Debug.WriteLine(
                    "\tDataContext: {0} {1}",
                    frameworkElement.DataContext,
                    frameworkElement.DataContext != null
                        ? "HashCode: " + frameworkElement.DataContext.GetHashCode()
                        : "");

                // List common layout properties
                if (!double.IsNaN(frameworkElement.Width) ||
                    !double.IsNaN(frameworkElement.Height))
                {
                    Debug.WriteLine(
                        "\tWidth={0}\r\n\tHeight={1}",
                        frameworkElement.Width,
                        frameworkElement.Height);
                }

                if (scrollViewer != null)
                {
                    Debug.WriteLine(
                        "\tScrollViewer.HorizontalOffset={0}\r\n\tScrollViewer.ViewportWidth={1}\r\n\tScrollViewer.ExtentWidth={2}\r\n\tScrollViewer.VerticalOffset={3}\r\n\tScrollViewer.ViewportHeight={4}\r\n\tScrollViewer.ExtentHeight={5}",
                        scrollViewer.HorizontalOffset,
                        scrollViewer.ViewportWidth,
                        scrollViewer.ExtentWidth,
                        scrollViewer.VerticalOffset,
                        scrollViewer.ViewportHeight,
                        scrollViewer.ExtentHeight
                        );
                }

                if (frameworkElement.MinWidth > 0 ||
                    frameworkElement.MinHeight > 0 ||
                    !double.IsInfinity(frameworkElement.MaxWidth) ||
                    !double.IsInfinity(frameworkElement.MaxHeight))
                {
                    Debug.WriteLine(
                        "\tMinWidth={0}\r\n\tMaxWidth={1}\r\n\tMinHeight={2}\r\n\tMaxHeight={3}",
                        frameworkElement.MinWidth,
                        frameworkElement.MaxWidth,
                        frameworkElement.MinHeight,
                        frameworkElement.MaxHeight);
                }

                Debug.WriteLine(
                    "\tHorizontalAlignment={0}\r\n\tVerticalAlignment={1}",
                    frameworkElement.HorizontalAlignment,
                    frameworkElement.VerticalAlignment);

                if (cc != null)
                {
                    Debug.WriteLine(
                        "\tHorizontalContentAlignment={0}\r\n\tVerticalContentAlignment={1}\r\n\tContent={2}",
                        cc.HorizontalContentAlignment,
                        cc.VerticalContentAlignment,
                        cc.Content ?? "<null>");
                }

                Debug.WriteLine(
                    "\tMargins={0},{1},{2},{3}",
                    frameworkElement.Margin.Left,
                    frameworkElement.Margin.Top,
                    frameworkElement.Margin.Right,
                    frameworkElement.Margin.Bottom);

                if (cc != null)
                {
                    Debug.WriteLine("\tPadding={0}", cc.Padding);
                }

                if (panel != null)
                {
                    Debug.WriteLine("\tBackground={0}", BrushToString(panel.Background));
                }
                else if (c != null)
                {
                    Debug.WriteLine("\tBackground={0}", BrushToString(c.Background));
                    Debug.WriteLine("\tForeground={0}", BrushToString(c.Foreground));
                }

                if (parentGrid != null)
                {
                    var col = Grid.GetColumn(frameworkElement);
                    var row = Grid.GetRow(frameworkElement);

                    if (parentGrid.ColumnDefinitions.Count != 0 || col != 0)
                    {
                        Debug.Assert(
                            col < parentGrid.ColumnDefinitions.Count,
                            string.Format(
                                "Column {0} not defined on the parent Grid!", col));
                        col = Math.Min(col, parentGrid.ColumnDefinitions.Count - 1);
                        Debug.WriteLine(
                            "\tColumn: {0} ({1})",
                            col,
                            parentGrid.ColumnDefinitions[col].Width);
                    }

                    if (parentGrid.RowDefinitions.Count != 0 || row != 0)
                    {
                        Debug.Assert(
                            row < parentGrid.RowDefinitions.Count,
                            string.Format(
                                "Row {0} not defined on the parent Grid!", row));
                        row = Math.Min(row, parentGrid.RowDefinitions.Count - 1);
                        Debug.WriteLine(
                            "\tRow: {0} ({1})",
                            row,
                            parentGrid.RowDefinitions[row].Height);
                    }
                }

                if (c != null)
                {
                    Debug.WriteLine("\tFontFamily: {0}", c.FontFamily.Source);
                }

                if (image != null)
                {
                    Debug.WriteLine("\tImage\n  Source: {0}", image.Source);

                    var bs = image.Source as BitmapSource;
                    var bi = image.Source as BitmapImage;

                    if (bi != null)
                    {
                        Debug.WriteLine("\t\tSource.UriSource: {0}", bi.UriSource.OriginalString);
                    }

                    if (bs != null)
                    {
                        Debug.WriteLine("\t\tPixelWidth: {0}", bs.PixelWidth);
                        Debug.WriteLine("\t\tPixelHeight: {0}", bs.PixelHeight);
                    }
                }

                if (frameworkElement.Parent is Canvas)
                {
                    var x = Canvas.GetLeft(frameworkElement);
                    var y = Canvas.GetTop(frameworkElement);
                    var zIndex = Canvas.GetZIndex(frameworkElement);

                    Debug.WriteLine(
                        "\tCanvas – X={0}, Y={1}, ZIndex={2}", x, y, zIndex);
                }
            }
        }
Example #14
0
        /// <summary>
        /// Attaches an instance of a DependencyObject to this instance
        /// </summary>
        /// <param name="dependencyObject">The instance to attach</param>
        public void Attach(DependencyObject dependencyObject)
        {
            AssociatedObject = dependencyObject;

            if (!string.IsNullOrEmpty(EventName))
            {
                EventWrapper eventHooker = new EventWrapper(this);
                eventHooker.AssociatedObject = dependencyObject;
                EventInfo eventInfo = GetEventInfo(dependencyObject.GetType(), EventName);

                if (eventInfo != null)
                {
                    Delegate handler = eventHooker.GetEventHandler(eventInfo);

                    WindowsRuntimeMarshal.AddEventHandler<Delegate>(
                        dlg => (EventRegistrationToken)eventInfo.AddMethod.Invoke(dependencyObject, new object[] { dlg }),
                        etr => eventInfo.RemoveMethod.Invoke(dependencyObject, new object[] { etr }), handler);
                }
            }
        }
        private static void UpdateProperties(DependencyObject attachedObject, string properties, string uid)
        {
            #if DEBUG
            if (DesignMode.DesignModeEnabled)
            {
                return;
            }
            #endif
            IEnumerable<string> props = properties.Split(',');

            Type attachedType = attachedObject.GetType();
            bool hasProperties = props.Any();

            foreach (PropertyInfo propInfo in props.Select(attachedType.GetRuntimeProperty).Where(propInfo => propInfo != null))
            {
                string value = hasProperties ? ResourceService.GetString(uid, properties) : ResourceService.GetString(uid);
                propInfo.SetValue(attachedObject, value);
            }
        }
        /// <summary>
        /// Method that will create the region, by calling the right <see cref="IRegionAdapter"/>. 
        /// </summary>
        /// <param name="targetElement">The target element that will host the <see cref="IRegion"/>.</param>
        /// <param name="regionName">Name of the region.</param>
        /// <returns>The created <see cref="IRegion"/></returns>
        protected virtual IRegion CreateRegion(DependencyObject targetElement, string regionName)
        {
            if (targetElement == null) throw new ArgumentNullException("targetElement");
            try {
                // Build the region
                IRegionAdapter regionAdapter = this.regionAdapterMappings.GetMapping(targetElement.GetType());
                IRegion region = regionAdapter.Initialize(targetElement, regionName);

                return region;
            }
            catch (Exception ex) {
                throw new RegionCreationException(string.Format(CultureInfo.CurrentCulture, ResourceHelper.RegionCreationException, regionName, ex), ex);
            }
        }
Example #17
0
        private static void CmdChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
            var t = d.GetType();
            var evtName = GetEvent((FrameworkElement)d);
            var evt = t.GetEvent(evtName);

            if (evt != null) {
                //Adding or removing event handlers dynamically is not supported on WinRT events.
                //evt.AddEventHandler(d, new TypedEventHandler<DependencyObject, object>(EventDelegate));

                // http://stackoverflow.com/questions/16647198/how-to-dynamically-bind-event-to-command-in-winrt-without-reactive-framework

                var addMethod = evt.AddMethod;
                var removeMethod = evt.RemoveMethod;
                var addParameters = addMethod.GetParameters();
                var delegateType = addParameters[0].ParameterType;
                Action<object, object> handler = (sender, args) => {
                    ////sender maybe not attached objected.
                    //FireCommand(sender, args as RoutedEventArgs);

                    FireCommand(d, args);
                };
                var invoke = typeof(Action<object, object>).GetRuntimeMethod("Invoke", new[] { typeof(object), typeof(object) });
                var @delegate = invoke.CreateDelegate(delegateType, handler);

                try {
                    Func<object, EventRegistrationToken> add = a => (EventRegistrationToken)addMethod.Invoke(d, new object[] { @delegate });
                    Action<EventRegistrationToken> remove = tt => removeMethod.Invoke(d, new object[] { tt });

                    WindowsRuntimeMarshal.AddEventHandler(add, remove, handler);
                } catch {

                }
            }
        }
Example #18
0
        private static void OnExceptionRoutedEventChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            string routedEvent = (string)e.NewValue;

            if (!string.IsNullOrEmpty(routedEvent))
            {
                EventHooker eventHooker = new EventHooker();
                eventHooker.ControlCommandObject = d;
                EventInfo eventInfo = GetEventInfo(d.GetType(), routedEvent);

                if (eventInfo != null)
                {
                    eventInfo.AddEventHandler(d, eventHooker.GetEventHandler(eventInfo));
                }

            }
        }
        /// <summary>
        /// Handler for the registered event property.
        /// </summary>
        /// <param name="d"></param>
        /// <param name="e"></param>
        private static void OnEventPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d != null && e.NewValue != null && !string.IsNullOrEmpty(((TealiumEvent)e.NewValue).EventName))
            {
                var evt = d.GetType().GetRuntimeEvent(((TealiumEvent)e.NewValue).EventName);
                if (evt != null)
                {
                    RegisterForEvent(d, evt);

                }
            }
            if (d != null && e.OldValue != null && !string.IsNullOrEmpty(((TealiumEvent)e.OldValue).EventName))
            {
                var oldEvt = d.GetType().GetRuntimeEvent(((TealiumEvent)e.OldValue).EventName);
                if (oldEvt != null)
                {
                    UnregisterForEvent(d, oldEvt);
                }
            }
        }
Example #20
0
        //public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(CommandExecuter), new PropertyMetadata(CommandPropertyChangedCallback));

        //public static readonly DependencyProperty OnEventProperty = DependencyProperty.RegisterAttached("OnEvent", typeof(string), typeof(CommandExecuter));

        //public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.RegisterAttached("CommandParameter", typeof(object), typeof(CommandExecuter));

        public static void CommandPropertyChangedCallback(DependencyObject depObj, DependencyPropertyChangedEventArgs args)
        {
            string onEvent = (string)depObj.GetValue(OnEventProperty);
            //Debug.Assert(onEvent != null, "OnEvent must be set.");
            var eventInfo = depObj.GetType().GetEvent(onEvent);
            if (eventInfo != null)
            {
                var mInfo = typeof(CommandExecuter).GetMethod("OnRoutedEvent", BindingFlags.NonPublic | BindingFlags.Static);
                eventInfo.GetAddMethod().Invoke(depObj, new object[] { mInfo.CreateDelegate(eventInfo.EventHandlerType) });
            }
            else
            {
                //Debug.Fail(string.Format("{0} is not found on object {1}", onEvent, depObj.GetType()));

            }

        }