예제 #1
0
        /// <summary>
        /// Called when the <see cref="DropDown"/> property changed.
        /// </summary>
        /// <param name="oldValue">The old value.</param>
        /// <param name="newValue">The new value.</param>
        protected virtual void OnDropDownChanged(FrameworkElement oldValue, FrameworkElement newValue)
        {
            // Remove previous drop-down element.
            if (_contextMenu != null)
            {
                if (_contextMenuRoot != null)
                {
                    RemoveLogicalChild(_contextMenuRoot);
                    _contextMenuRoot = null;
                }

                BindingOperations.ClearBinding(_contextMenu, ContextMenu.IsOpenProperty);
                _contextMenu.ClearValue(ContextMenu.PlacementProperty);
                _contextMenu.ClearValue(ContextMenu.PlacementTargetProperty);
                _contextMenu = null;
            }
            else if (_popup != null)
            {
                RemoveLogicalChild(_popup);

                _popup.Opened             -= OnPopupOpened;
                _popup.MouseDown          -= OnPopupMouseDown;
                _popup.ContextMenuOpening -= OnPopupContextMenuOpening;
                BindingOperations.ClearBinding(_popup, Popup.IsOpenProperty);
                _popup.ClearValue(Popup.PlacementProperty);
                _popup.ClearValue(Popup.PlacementTargetProperty);
                _popup = null;
            }

            // Use new drop-down element.
            _contextMenu = newValue as ContextMenu;
            if (_contextMenu != null)
            {
                _contextMenu.Placement       = PlacementMode.Bottom;
                _contextMenu.PlacementTarget = this;
                BindToIsDropDownOpen(_contextMenu, ContextMenu.IsOpenProperty);

                // Add as logical child for data binding and routed commands.
                _contextMenu.IsOpen = true;
                DependencyObject element = _contextMenu;
                do
                {
                    _contextMenuRoot = element;
                    element          = LogicalTreeHelper.GetParent(element);
                } while (null != element);
                _contextMenu.IsOpen = false;
                AddLogicalChild(_contextMenuRoot);
            }
            else
            {
                _popup = newValue as Popup;
                if (_popup == null)
                {
                    _popup = new Popup
                    {
                        AllowsTransparency = true,
                        Child = new SystemDropShadowChrome
                        {
                            Color  = SystemParameters.DropShadow ? Color.FromArgb(113, 0, 0, 0) : Colors.Transparent,
                            Margin = SystemParameters.DropShadow ? new Thickness(0, 0, 5, 5) : new Thickness(0),
                            SnapsToDevicePixels = true,
                            Child = newValue
                        }
                    };
                }
                _popup.Placement       = PlacementMode.Bottom;
                _popup.PlacementTarget = this;
                BindToIsDropDownOpen(_popup, Popup.IsOpenProperty);
                _popup.Opened    += OnPopupOpened;
                _popup.MouseDown += OnPopupMouseDown;

                // We need to stop the context menu of the drop down button or its ancestors from
                // opening in the popup.
                if (_popup.ContextMenu == null)
                {
                    _popup.ContextMenuOpening += OnPopupContextMenuOpening;
                }

                // Add as logical child for data binding and routed commands.
                AddLogicalChild(_popup);
            }
        }
예제 #2
0
 internal virtual ResizingPanel GetContainerPanel()
 {
     return(LogicalTreeHelper.GetParent(this) as ResizingPanel);
 }
예제 #3
0
 public static DependencyObject GetLogicalParent(this DependencyObject obj)
 {
     return(LogicalTreeHelper.GetParent(obj));
 }
예제 #4
0
 // ------------------------------------------------------------------
 // GetBaselineAlignmentForInlineObject
 // ------------------------------------------------------------------
 internal static BaselineAlignment GetBaselineAlignmentForInlineObject(DependencyObject element)
 {
     return(GetBaselineAlignment(LogicalTreeHelper.GetParent(element)));
 }
예제 #5
0
        /// <summary>
        /// Gets a value indicating whether the specified UI element has an ancestor that matches the specified selector part.
        /// </summary>
        /// <param name="element">The UI element to evaluate. If a match is found, this variable will be updated to contain the matching element.</param>
        /// <param name="part">The selector part to evaluate.</param>
        /// <param name="root">The topmost root element to consider when tracing ancestors.</param>
        /// <param name="qualifier">A qualifier which specifies the relationship between the element and its ancestor.</param>
        /// <returns><see langword="true"/> if the element matches the selector part; otherwise, <see langword="false"/>.</returns>
        private static Boolean AncestorMatchesSelectorPart(ref UIElement element, UvssSelectorPart part, UIElement root, UvssSelectorPartQualifier qualifier)
        {
            if (qualifier == UvssSelectorPartQualifier.TemplatedChild)
            {
                var fe = element as FrameworkElement;
                if (fe != null && fe.TemplatedParent != null)
                {
                    var feTemplatedParent = (UIElement)fe.TemplatedParent;
                    if (ElementMatchesSelectorPart(feTemplatedParent, feTemplatedParent, part))
                    {
                        element = feTemplatedParent;
                        return(true);
                    }
                }
                return(false);
            }
            else
            {
                var current = element;
                while (true)
                {
                    if (current == root)
                    {
                        return(false);
                    }

                    current = ((qualifier == UvssSelectorPartQualifier.LogicalChild) ? LogicalTreeHelper.GetParent(current) : VisualTreeHelper.GetParent(current)) as UIElement;
                    if (current == null)
                    {
                        break;
                    }

                    if (ElementMatchesSelectorPart(root, current, part))
                    {
                        element = current;
                        return(true);
                    }

                    if (qualifier != UvssSelectorPartQualifier.None)
                    {
                        break;
                    }
                }
                return(false);
            }
        }
예제 #6
0
        /// <summary>
        /// Retrieves the range of a child object.
        /// </summary>
        /// <param name="childElementProvider">The child element.  A provider should check that the
        /// passed element is a child of the text container, and should throw an
        /// InvalidOperationException if it is not.</param>
        /// <returns>A range that spans the child element.</returns>
        ITextRangeProvider ITextProvider.RangeFromChild(IRawElementProviderSimple childElementProvider)
        {
            if (childElementProvider == null)
            {
                throw new ArgumentNullException("childElementProvider");
            }

            // Retrieve DependencyObject from AutomationElement
            DependencyObject childElement;

            if (_textPeer is TextAutomationPeer)
            {
                childElement = ((TextAutomationPeer)_textPeer).ElementFromProvider(childElementProvider);
            }
            else
            {
                childElement = ((ContentTextAutomationPeer)_textPeer).ElementFromProvider(childElementProvider);
            }

            TextRangeAdaptor range = null;

            if (childElement != null)
            {
                ITextPointer rangeStart = null;
                ITextPointer rangeEnd   = null;

                // Retrieve start and end positions for given element.
                // If element is TextElement, retrieve its Element Start and End positions.
                // If element is UIElement hosted by UIContainer (Inlien of Block),
                // retrieve content Start and End positions of the container.
                // Otherwise scan ITextContainer to find a range for given element.
                if (childElement is TextElement)
                {
                    rangeStart = ((TextElement)childElement).ElementStart;
                    rangeEnd   = ((TextElement)childElement).ElementEnd;
                }
                else
                {
                    DependencyObject parent = LogicalTreeHelper.GetParent(childElement);
                    if (parent is InlineUIContainer || parent is BlockUIContainer)
                    {
                        rangeStart = ((TextElement)parent).ContentStart;
                        rangeEnd   = ((TextElement)parent).ContentEnd;
                    }
                    else
                    {
                        ITextPointer position = _textContainer.Start.CreatePointer();
                        while (position.CompareTo(_textContainer.End) < 0)
                        {
                            TextPointerContext context = position.GetPointerContext(LogicalDirection.Forward);
                            if (context == TextPointerContext.ElementStart)
                            {
                                if (childElement == position.GetAdjacentElement(LogicalDirection.Forward))
                                {
                                    rangeStart = position.CreatePointer(LogicalDirection.Forward);
                                    position.MoveToElementEdge(ElementEdge.AfterEnd);
                                    rangeEnd = position.CreatePointer(LogicalDirection.Backward);
                                    break;
                                }
                            }
                            else if (context == TextPointerContext.EmbeddedElement)
                            {
                                if (childElement == position.GetAdjacentElement(LogicalDirection.Forward))
                                {
                                    rangeStart = position.CreatePointer(LogicalDirection.Forward);
                                    position.MoveToNextContextPosition(LogicalDirection.Forward);
                                    rangeEnd = position.CreatePointer(LogicalDirection.Backward);
                                    break;
                                }
                            }
                            position.MoveToNextContextPosition(LogicalDirection.Forward);
                        }
                    }
                }
                // Create range
                if (rangeStart != null && rangeEnd != null)
                {
                    range = new TextRangeAdaptor(this, rangeStart, rangeEnd, _textPeer);
                }
            }
            if (range == null)
            {
                throw new InvalidOperationException(SR.Get(SRID.TextProvider_InvalidChildElement));
            }
            return(range);
        }
 public static T GetResource <T>(this DependencyObject element, object key)
 {
     for (var dependencyObject = element; dependencyObject != null; dependencyObject = (LogicalTreeHelper.GetParent(dependencyObject) ?? VisualTreeHelper.GetParent(dependencyObject)))
     {
         var frameworkElement = dependencyObject as FrameworkElement;
         if (frameworkElement != null)
         {
             if (frameworkElement.Resources.Contains(key))
             {
                 return((T)frameworkElement.Resources[key]);
             }
         }
         else
         {
             var frameworkContentElement = dependencyObject as FrameworkContentElement;
             if (frameworkContentElement != null && frameworkContentElement.Resources.Contains(key))
             {
                 return((T)frameworkContentElement.Resources[key]);
             }
         }
     }
     if (Application.Current != null && Application.Current.Resources.Contains(key))
     {
         return((T)Application.Current.Resources[key]);
     }
     return(default(T));
 }
예제 #8
0
 public static DependencyObject GetParent(this DependencyObject obj)
 {
     return(obj is Visual?VisualTreeHelper.GetParent(obj) : LogicalTreeHelper.GetParent(obj));
 }
예제 #9
0
        async void PasswordRequire_Loaded(object sender, RoutedEventArgs e)
        {
            Process[]        currentProcess = Process.GetProcesses();
            List <string>    process        = new List <string>();
            MessageBoxResult result         = MessageBoxResult.None;

            foreach (Process pro in currentProcess)
            {
                if (pro.ProcessName == "SocialSilence")
                {
                    process.Add(pro.ProcessName);
                }
            }
            if (process.Count() != 1 && process.Count() != 0)     // Checking for Instances of current application running .
            {
                result = Xceed.Wpf.Toolkit.MessageBox.Show("There are current Instances of same Application running on this computer.", "Message", MessageBoxButton.OK);

                if (result == MessageBoxResult.OK)
                {
                    App.Current.MainWindow.Close();
                }
            }



            Rect workArea = System.Windows.SystemParameters.WorkArea;

            App.Current.MainWindow.Left = workArea.Left + (workArea.Width - this.WindowWidth) / 2;
            App.Current.MainWindow.Top  = workArea.Top + (workArea.Height - this.WindowHeight) / 2;
            ((NavigationWindow)LogicalTreeHelper.GetParent(this)).ResizeMode = ResizeMode.CanMinimize;
            NavigationWindow win = (NavigationWindow)Window.GetWindow(this);

            win.Closing += win_Closing;

            var OSname = (from x in new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem").Get().OfType <ManagementObject>()
                          select x.GetPropertyValue("Caption")).FirstOrDefault();

            if (OSname.ToString().Contains("Windows 8"))
            {
                string[] languageSet = (string[])Registry.GetValue(@"HKEY_CURRENT_USER\Control Panel\International\User Profile", "Languages", null);
                if (languageSet[0].Length > 2)
                {
                    userLanguage = languageSet[0].Remove(2);
                }
                else
                {
                    userLanguage = languageSet[0];
                }
            }
            else if (OSname.ToString().Contains("Windows 7"))
            {
                string[] languageSet = (string[])Registry.GetValue(@"HKEY_CURRENT_USER\Control Panel\Desktop\MuiCached", "MachinePreferredUILanguages", null);
                if (languageSet[0].Length > 2)
                {
                    userLanguage = languageSet[0].Remove(2);
                }
                else
                {
                    userLanguage = languageSet[0];
                }
            }


            SetLanguageDictionary(userLanguage);
            this.KeyDown += new KeyEventHandler(KeyPress);

            try
            {
                IconHandles = new Dictionary <string, System.Drawing.Icon>();
                IconHandles.Add("QuickLaunch", new System.Drawing.Icon(Environment.CurrentDirectory + @"\resources\error.ico"));
                notifyIcon                 = new System.Windows.Forms.NotifyIcon();
                notifyIcon.Click          += notifyIcon_Click;
                notifyIcon.Icon            = IconHandles["QuickLaunch"];
                notifyIcon.BalloonTipTitle = "Social Silence";
                notifyIcon.BalloonTipText  = (string)FindResource("ClickIcon");;
                notifyIcon.Visible         = true;
                notifyIcon.ShowBalloonTip(500);
                notificationToolTip = (string)FindResource("ApplicationInactive");
                setNotifyIconText(notifyIcon, notificationToolTip);
                // System.Windows.Forms.ContextMenu menu = notifyIcon.ContextMenu;
                // System.Windows.Forms.MenuItem item3 = menu.MenuItems[3];
                //item3.Visible = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show("An exception created while creating the taskbar icon " + ex.Message + ex.StackTrace);
            }

            try
            {
                IsolatedStorageFile password = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, null, null);
                filePath = password.GetType().GetField("m_RootDir", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(password).ToString();
                if (!File.Exists(filePath + "host"))
                {
                    firstRun = true;
                }
                using (StreamReader passReader = new StreamReader(new IsolatedStorageFileStream("Win32AppPas.bin", FileMode.OpenOrCreate, password)))
                {
                    // File.SetAttributes(filePath + "Win32AppPas.bin", FileAttributes.Hidden|FileAttributes.System);
                    File.SetAttributes(filePath + "Win32AppPas.bin", FileAttributes.Normal);
                    if (passReader != null)
                    {
                        string p = await passReader.ReadToEndAsync();

                        if (p == null || p == "")                                  // If there is no password in the file then the application is going to start from Start Page.
                        {
                            notifyIcon.Click -= notifyIcon_Click;
                            StartPage pobj = new StartPage();
                            this.NavigationService.Navigate(pobj);
                        }
                        else
                        {
                            passwordStored = p;
                        }
                    }
                }
                File.SetAttributes(filePath + "Win32AppPas.bin", FileAttributes.Hidden | FileAttributes.System);
            }
            catch (Exception ex)
            {
                MessageBox.Show("An exception occured while opening the password from the file . " + ex.Message + ex.StackTrace);
            }
        }
예제 #10
0
파일: ObjectRef.cs 프로젝트: beda2280/wpf-1
        //------------------------------------------------------
        //
        //  Public Methods
        //
        //------------------------------------------------------

        /// <summary> Returns the referenced object. </summary>
        /// <param name="d">Element defining context for the reference. </param>
        /// <param name="args">See ObjectRefArgs </param>
        internal override object GetObject(DependencyObject d, ObjectRefArgs args)
        {
            if (d == null)
            {
                throw new ArgumentNullException("d");
            }

            object o = null;

            if (args.ResolveNamesInTemplate)
            {
                // look in container's template (if any) first
                FrameworkElement fe = d as FrameworkElement;
                if (fe != null && fe.TemplateInternal != null)
                {
                    o = Helper.FindNameInTemplate(_name, d);

                    if (args.IsTracing)
                    {
                        TraceData.Trace(TraceEventType.Warning,
                                        TraceData.ElementNameQueryTemplate(
                                            _name,
                                            TraceData.Identify(d)));
                    }
                }

                if (o == null)
                {
                    args.NameResolvedInOuterScope = true;
                }
            }

            FrameworkObject fo = new FrameworkObject(d);

            while (o == null && fo.DO != null)
            {
                DependencyObject scopeOwner;
                o = fo.FindName(_name, out scopeOwner);

                // if the original element is a scope owner, supports IComponentConnector,
                // and has a parent, don't use the result of FindName.  The
                // element is probably an instance of a Xaml-subclassed control;
                // we want to resolve the name starting in the next outer scope.
                // (bug 1669408)
                // Also, if the element's NavigationService property is locally
                // set, the element is the root of a navigation and should use the
                // inner scope (bug 1765041)
                if (d == scopeOwner && d is IComponentConnector &&
                    d.ReadLocalValue(System.Windows.Navigation.NavigationService.NavigationServiceProperty) == DependencyProperty.UnsetValue)
                {
                    DependencyObject parent = LogicalTreeHelper.GetParent(d);
                    if (parent == null)
                    {
                        parent = Helper.FindMentor(d.InheritanceContext);
                    }

                    if (parent != null)
                    {
                        o = null;
                        fo.Reset(parent);
                        continue;
                    }
                }

                if (args.IsTracing)
                {
                    TraceData.Trace(TraceEventType.Warning,
                                    TraceData.ElementNameQuery(
                                        _name,
                                        TraceData.Identify(fo.DO)));
                }

                if (o == null)
                {
                    args.NameResolvedInOuterScope = true;

                    // move to the next outer namescope.
                    // First try TemplatedParent of the scope owner.
                    FrameworkObject  foScopeOwner = new FrameworkObject(scopeOwner);
                    DependencyObject dd           = foScopeOwner.TemplatedParent;

                    // if that doesn't work, we could be at the top of
                    // generated content for an ItemsControl.  If so, use
                    // the (visual) parent - a panel.
                    if (dd == null)
                    {
                        Panel panel = fo.FrameworkParent.DO as Panel;
                        if (panel != null && panel.IsItemsHost)
                        {
                            dd = panel;
                        }
                    }

                    // if the logical parent is a ContentControl whose content
                    // points right back, move to the ContentControl.   This is the
                    // moral equivalent of having the ContentControl as the TemplatedParent.
                    // (The InheritanceBehavior clause prevents this for cases where the
                    // parent ContentControl imposes a barrier, e.g. Frame)
                    if (dd == null && scopeOwner == null)
                    {
                        ContentControl cc = LogicalTreeHelper.GetParent(fo.DO) as ContentControl;
                        if (cc != null && cc.Content == fo.DO && cc.InheritanceBehavior == InheritanceBehavior.Default)
                        {
                            dd = cc;
                        }
                    }

                    // next, see if we're in a logical tree attached directly
                    // to a ContentPresenter.  This is the moral equivalent of
                    // having the ContentPresenter as the TemplatedParent.
                    if (dd == null && scopeOwner == null)
                    {
                        // go to the top of the logical subtree
                        DependencyObject parent;
                        for (dd = fo.DO; ;)
                        {
                            parent = LogicalTreeHelper.GetParent(dd);
                            if (parent == null)
                            {
                                parent = Helper.FindMentor(dd.InheritanceContext);
                            }

                            if (parent == null)
                            {
                                break;
                            }

                            dd = parent;
                        }

                        // if it's attached to a ContentPresenter, move to the CP
                        ContentPresenter cp = VisualTreeHelper.IsVisualType(dd) ? VisualTreeHelper.GetParent(dd) as ContentPresenter : null;
                        dd = (cp != null && cp.TemplateInternal.CanBuildVisualTree) ? cp : null;
                    }

                    fo.Reset(dd);
                }
            }

            if (o == null)
            {
                o = DependencyProperty.UnsetValue;
                args.NameResolvedInOuterScope = false;
            }

            return(o);
        }
예제 #11
0
        private bool UpdateWatcherAndData_Fe(DependencyObject targetObject, string pathElement,
                                             bool isTargetADc, string binderName)
        {
            if (SourceKind != SourceKindEnum.FrameworkElement && SourceKind != SourceKindEnum.FrameworkContentElement)
            {
                throw new InvalidOperationException($"Cannot call {nameof(UpdateWatcherAndData_Fe)} " +
                                                    $"if the ObservableSource does not have a SourceKind of {nameof(SourceKindEnum.FrameworkElement)} " +
                                                    $"or {nameof(SourceKindEnum.FrameworkContentElement)}.");
            }

            string fwElementName = LogicalTree.GetNameFromDepObject(targetObject);

            System.Diagnostics.Debug.WriteLine($"Fetching DataContext to use from: {fwElementName} for pathElement: {pathElement}.");

            this.IsTargetADc = isTargetADc;

            // If this binding sets a DataContext, watch the TargetObject's parent, otherwise watch the TargetObject for DataContext updates

            // TODO: May want to make sure that the value of Container is a DependencyObject.
            DependencyObject curContainer = (DependencyObject)Container;
            DependencyObject newContainer = isTargetADc ? LogicalTreeHelper.GetParent(targetObject) : targetObject;

            if (!object.ReferenceEquals(curContainer, newContainer))
            {
                SubscribeTo_FcOrFce(newContainer, DataContextChanged_Fe);
                Container = newContainer;
            }

            // Now see if we can find a data context.
            DependencyObject foundNode = LogicalTree.GetDataContext(targetObject, out bool foundIt,
                                                                    startWithParent: isTargetADc, inspectAncestors: true, stopOnNodeWithBoundDc: true);

            if (!foundIt)
            {
                bool changed = UpdateData(null, null, ObservableSourceStatusEnum.NoType);
                return(changed);
            }

            if (!object.ReferenceEquals(targetObject, foundNode))
            {
                string foundFwElementName = LogicalTree.GetNameFromDepObject(foundNode);
                System.Diagnostics.Debug.WriteLine($"Found DataContext to watch using an ancestor: {foundFwElementName} for pathElement: {pathElement}.");
            }
            else
            {
                System.Diagnostics.Debug.WriteLine($"Found DataContext to watch on the target object for pathElement: {pathElement}.");
            }

            DependencyObject foundNodeWithBoundDc = LogicalTree.GetDataContextWithBoundDc(targetObject,
                                                                                          out bool foundOneWithBoundDc, startWithParent: isTargetADc);

            if (foundOneWithBoundDc)
            {
                System.Diagnostics.Debug.WriteLine("Some parent has a DataContext that is set via a Binding Markup.");
            }

            if (foundNode is FrameworkElement fe)
            {
                Type newType = fe.DataContext?.GetType();
                ObservableSourceStatusEnum newStatus = Status.SetReady(fe.DataContext != null);

                bool changed = UpdateData(fe.DataContext, newType, newStatus);
                //if(newType.IsIListSource())
                //{
                //    changed = UpdateData(((IListSource)fe.DataContext).GetList(), newType, newStatus);
                //}
                //else
                //{
                //    changed = UpdateData(fe.DataContext, newType, newStatus);
                //}

                return(changed);
            }
            else if (foundNode is FrameworkContentElement fce)
            {
                Type newType = fce.DataContext?.GetType();
                ObservableSourceStatusEnum newStatus = Status.SetReady(fce.DataContext != null);
                bool changed = UpdateData(fce.DataContext, newType, newStatus);
                return(changed);
            }
            else
            {
                throw new ApplicationException($"Found node in {binderName}.ObservableSourceProvider was neither a FrameworkElement or a FrameworkContentElement.");
            }
        }
예제 #12
0
 public static DependencyObject GetVisualOrLogicalParent(this DependencyObject sourceElement)
 {
     if (sourceElement == null)
     {
         return(null);
     }
     return(sourceElement is Visual?VisualTreeHelper.GetParent(sourceElement) ?? LogicalTreeHelper.GetParent(sourceElement) : LogicalTreeHelper.GetParent(sourceElement));
 }
예제 #13
0
 /// <summary>
 /// Returns either the visual or logical parent of <paramref name="element"/>.
 /// This also works for <see cref="ContentElement"/> and <see cref="FrameworkContentElement"/>.
 /// </summary>
 public static DependencyObject GetVisualOrLogicalParent(DependencyObject element)
 {
     return(GetVisualParent(element) ?? LogicalTreeHelper.GetParent(element));
 }
예제 #14
0
        public static DependencyObject FindVisualTreeRoot(this DependencyObject initial)
        {
            DependencyObject dependencyObject = initial;
            DependencyObject result           = initial;

            while (dependencyObject != null)
            {
                result           = dependencyObject;
                dependencyObject = ((!(dependencyObject is Visual) && !(dependencyObject is Visual3D)) ? LogicalTreeHelper.GetParent(dependencyObject) : VisualTreeHelper.GetParent(dependencyObject));
            }

            return(result);
        }
예제 #15
0
        private void OnMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount == 2 && e.LeftButton == MouseButtonState.Pressed)
            {
                var port = sender as ExtendedPort;
                if (port == null)
                {
                    return;
                }

                // Get the ExtendedVplControl as Host UserControl
                DependencyObject ucParent = Parent;

                while (!(ucParent is PortArea))
                {
                    ucParent = LogicalTreeHelper.GetParent(ucParent);
                }
                var portArea = ucParent as PortArea;
                if (portArea == null)
                {
                    return;
                }

                try
                {
                    // Remove Connections, the port itself and recompute the port positions ...
                    foreach (var item in port.ConnectedConnectors)
                    {
                        item.RemoveFromCanvas();
                    }

                    port.UpdateLayout();
                    // portArea.PortControl.Children.Remove(port);
                    portArea.RecalculateLocationForAllPorts();
                }
                catch (Exception)
                {
                }

                e.Handled = true;
            }
            // Remove the clicked port
            else if (e.ClickCount == 2 && e.RightButton == MouseButtonState.Pressed)
            {
                var port = sender as ExtendedPort;
                if (port == null)
                {
                    return;
                }

                // Get the ExtendedVplControl as Host UserControl
                DependencyObject ucParent = Parent;

                while (!(ucParent is PortArea))
                {
                    ucParent = LogicalTreeHelper.GetParent(ucParent);
                }
                var portArea = ucParent as PortArea;
                if (portArea == null)
                {
                    return;
                }

                try
                {
                    port.UpdateLayout();
                    portArea.PortControl.Children.Remove(port);
                    portArea.RecalculateLocationForAllPorts();
                }
                catch (Exception)
                {
                }

                e.Handled = true;
            }
        }
 // Token: 0x06007232 RID: 29234 RVA: 0x0020A030 File Offset: 0x00208230
 internal override void PrivateConnectChild(int index, TElementType item)
 {
     if (item.Parent is ContentElementCollection <TParent, TElementType> .DummyProxy && LogicalTreeHelper.GetParent(item.Parent) != base.Owner)
     {
         throw new ArgumentException(SR.Get("TableCollectionWrongProxyParent"));
     }
     base.Items[index] = item;
     item.Index        = index;
     item.OnEnterParentTree();
 }
예제 #17
0
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            IProvideValueTarget provideValue = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;

            if (provideValue == null || provideValue.TargetObject == null)
            {
                return(null);
                //                throw new NotSupportedException("The IProvideValueTarget is not supported");
            }
            if (provideValue.TargetObject.GetType().FullName == "System.Windows.SharedDp")
            {
                return(this);
            }

            DependencyObject targetObject = provideValue.TargetObject as DependencyObject;

            if (targetObject == null)
            {
                Debug.Fail(string.Format("can't persist type {0}, not a dependency object", provideValue.TargetObject));
                throw new NotSupportedException();
            }

            DependencyProperty targetProperty = provideValue.TargetProperty as DependencyProperty;

            if (targetProperty == null)
            {
                Debug.Fail(string.Format("can't persist type {0}, not a dependency property", provideValue.TargetProperty));
                throw new NotSupportedException();
            }
            Func <DependencyObject, Window> getParent = null;

            getParent = new Func <DependencyObject, Window>(ui => {
                var uie = ui;
                while (!(uie is Window) && uie != null)
                {
                    uie = LogicalTreeHelper.GetParent(uie);
                }
                if (uie == null)
                {
                    if (ui is UserControl)
                    {
                        var uc = ui as UserControl;
                        if (uc.Parent != null)
                        {
                            return(getParent(uc.Parent));
                        }
                        else
                        {
                            return(Application.Current.MainWindow);
                        }
                    }
                    return(ui is FrameworkElement ? getParent((ui as FrameworkElement).Parent) : null);
                }
                return(uie as Window);
            });
            #region key
            if (key == null)
            {
                IUriContext uriContext = (IUriContext)serviceProvider.GetService(typeof(IUriContext));
                if (uriContext == null)
                {
                    // fallback to default value if no key available
                    DependencyPropertyDescriptor descriptor = DependencyPropertyDescriptor.FromProperty(targetProperty, targetObject.GetType());
                    return(descriptor.GetValue(targetObject));
                }

                // UIElements have a 'PersistId' property that we can use to generate a unique key
                if (targetObject is UIElement)
                {
                    Func <DependencyObject, string, object> foo = (dp, name) => {
                        var en = dp.GetLocalValueEnumerator();
                        while (en.MoveNext())
                        {
                            if (en.Current.Property.Name.ToLower() == name.ToLower())
                            {
                                return(en.Current.Value);
                            }
                        }
                        return(null);
                    };
                    string persistID = (foo(targetObject, "Name") ?? ((UIElement)targetObject).PersistId) + "";
                    var    window    = getParent(targetObject as UIElement);
                    //System.Diagnostics.Debug.Assert(window!=null,"Main window is <Null>");
                    var windowName = window == null ? "" : window.Name;
                    key = string.Format("{0}.{1}[{2}.{3}]{4}",
                                        uriContext.BaseUri.PathAndQuery,
                                        targetObject.GetType().Name,
                                        windowName,
                                        persistID,
                                        targetProperty.Name);
                }
                // use parent-child relation to generate unique key
                else if (LogicalTreeHelper.GetParent(targetObject) is UIElement)
                {
                    UIElement parent = (UIElement)LogicalTreeHelper.GetParent(targetObject);
                    int       i      = 0;
                    foreach (object c in LogicalTreeHelper.GetChildren(parent))
                    {
                        if (c == targetObject)
                        {
                            key = string.Format("{0}.{1}[{2}].{3}[{4}].{5}",
                                                uriContext.BaseUri.PathAndQuery,
                                                parent.GetType().Name, parent.PersistId,
                                                targetObject.GetType().Name, i,
                                                targetProperty.Name);
                            break;
                        }
                        i++;
                    }
                }
                //TODO:should do something clever here to get a good key for tags like GridViewColumn

                if (key == null)
                {
                    Debug.Fail(string.Format("don't know how to automatically get a key for objects of type {0}\n use Key='...' option", targetObject.GetType()));

                    // fallback to default value if no key available
                    DependencyPropertyDescriptor descriptor = DependencyPropertyDescriptor.FromProperty(targetProperty, targetObject.GetType());
                    return(descriptor.GetValue(targetObject));
                }
                else
                {
                    //Debug.WriteLine(string.Format("key={0}", key));
                }
            }
            #endregion

            if (!UserSettingsStorage.Dictionary.ContainsKey(key))
            {
                UserSettingsStorage.Dictionary[key] = defaultValue;
            }

            object value = ConvertFromString(targetObject, targetProperty, UserSettingsStorage.Dictionary[key]);

            SetBinding(targetObject, targetProperty, key);

            return(value);
        }
예제 #18
0
 public DependencyObject GetParent(DependencyObject element)
 {
     return(LogicalTreeHelper.GetParent(element));
 }
        private void UserControl_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (this.Visibility == Visibility.Visible)
            {
                DependencyObject ucParent = this.Parent;

                while (!(ucParent is UserControl))
                {
                    ucParent = LogicalTreeHelper.GetParent(ucParent);
                }

                parent              = (receiptMng)ucParent;
                lstGuest            = UserController.loadDataGuest();
                cmbKH.ItemsSource   = lstGuest;
                cmbKH.SelectedIndex = 0;

                lstLB = receiptMngController.loadLichBayData();
                cmbMaCB.ItemsSource   = lstLB;
                cmbMaCB.SelectedIndex = 0;

                switch (parent.method)
                {
                case 1:    // Thêm
                {
                    addComboBtn.Visibility    = Visibility.Visible;
                    detailComboBtn.Visibility = Visibility.Hidden;
                    ManChe.Visibility         = Visibility.Hidden;
                    ManChe_2.Visibility       = Visibility.Hidden;

                    searchPanel.Visibility = Visibility.Visible;
                    btnAddGuest.Visibility = Visibility.Visible;


                    dpNgayMua.SelectedDate = DateTime.Today;
                    dpNgayMua.IsEnabled    = false;

                    txtNormalSeats.Text = "";
                    txtVIPSeats.Text    = "";

                    break;
                }

                case 2:    // Xem
                {
                    addComboBtn.Visibility    = Visibility.Hidden;
                    detailComboBtn.Visibility = Visibility.Visible;
                    btnCancel.Visibility      = Visibility.Hidden;

                    ManChe.Visibility   = Visibility.Visible;
                    ManChe_2.Visibility = Visibility.Visible;

                    searchPanel.Visibility = Visibility.Hidden;
                    btnAddGuest.Visibility = Visibility.Hidden;

                    cmbKH.ItemsSource = lstGuest;

                    KHACH guest = lstGuest.Where(x => x.ID == GlobalItem.selectedReceipt.MaKH).ToList().SingleOrDefault();

                    cmbKH.SelectedItem  = guest;
                    txtTenKH.Text       = guest.HoTen;
                    txtDialNumber2.Text = guest.SDT;

                    cmbMaCB.SelectedItem = lstLB.Where(x => x.MaCB == GlobalItem.selectedReceipt.MaCB && x.NgayDi == GlobalItem.selectedReceipt.NgayDi)
                                           .SingleOrDefault();

                    txtNormalSeats.Text = GlobalItem.selectedReceipt.SoVeThuong.ToString();
                    txtVIPSeats.Text    = GlobalItem.selectedReceipt.SoVeVip.ToString();
                    txtTongTien.Text    = GlobalItem.selectedReceipt.TongTien.ToString();

                    dpNgayMua.SelectedDate = GlobalItem.selectedReceipt.NgayMua;

                    break;
                }

                case 3:    // Sửa
                {
                    addComboBtn.Visibility    = Visibility.Hidden;
                    detailComboBtn.Visibility = Visibility.Visible;
                    btnCancel.Visibility      = Visibility.Visible;
                    ManChe.Visibility         = Visibility.Hidden;
                    ManChe_2.Visibility       = Visibility.Hidden;

                    searchPanel.Visibility = Visibility.Hidden;
                    btnAddGuest.Visibility = Visibility.Hidden;
                    cmbKH.ItemsSource      = lstGuest;

                    cmbKH.IsEnabled   = false;
                    cmbMaCB.IsEnabled = false;

                    KHACH guest = lstGuest.Where(x => x.ID == GlobalItem.selectedReceipt.MaKH).ToList().SingleOrDefault();
                    cmbKH.SelectedItem  = guest;
                    txtTenKH.Text       = guest.HoTen;
                    txtDialNumber2.Text = guest.SDT;

                    cmbMaCB.SelectedItem = lstLB.Where(x => x.MaCB == GlobalItem.selectedReceipt.MaCB && x.NgayDi == GlobalItem.selectedReceipt.NgayDi)
                                           .SingleOrDefault();

                    txtNormalSeats.Text = GlobalItem.selectedReceipt.SoVeThuong.ToString();
                    txtVIPSeats.Text    = GlobalItem.selectedReceipt.SoVeVip.ToString();

                    oriNormal = GlobalItem.selectedReceipt.SoVeThuong.Value;
                    oriVip    = GlobalItem.selectedReceipt.SoVeVip.Value;

                    txtTongTien.Text = GlobalItem.selectedReceipt.TongTien.ToString();

                    dpNgayMua.SelectedDate = GlobalItem.selectedReceipt.NgayMua;
                    break;
                }

                default: break;
                }
            }
            else
            {
                GlobalItem.selectedReceipt = null;
                dpNgayMua.IsEnabled        = true;
                cmbKH.IsEnabled            = true;
                cmbMaCB.IsEnabled          = true;
                txtTongTien.Text           = "";
                parent.loadDataHoaDon();
            }
        }
예제 #20
0
        public static DependencyObject GetLeastCommonAncestor(DependencyObject firstDescendant, DependencyObject secondDescendant, DependencyObject root)
        {
            DependencyObject current1   = firstDescendant;
            ArrayList        arrayList1 = new ArrayList();

            for (; current1 != null && LogicalTreeHelper.GetParent(current1) != null; current1 = LogicalTreeHelper.GetParent(current1))
            {
                arrayList1.Add((object)current1);
            }
            DependencyObject current2   = secondDescendant;
            ArrayList        arrayList2 = new ArrayList();

            for (; current2 != null && LogicalTreeHelper.GetParent(current2) != null; current2 = LogicalTreeHelper.GetParent(current2))
            {
                arrayList2.Add((object)current2);
            }
            DependencyObject dependencyObject = root;

            while (arrayList1.Count > 0 && arrayList2.Count > 0 && arrayList1[arrayList1.Count - 1] == arrayList2[arrayList2.Count - 1])
            {
                dependencyObject = (DependencyObject)arrayList1[arrayList1.Count - 1];
                arrayList1.RemoveAt(arrayList1.Count - 1);
                arrayList2.RemoveAt(arrayList2.Count - 1);
            }
            return(dependencyObject);
        }
예제 #21
0
        public static string GetContextByName(this DependencyObject dependencyObject)
        {
            string result = "";

            if (dependencyObject != null)
            {
                if (dependencyObject is UserControl || dependencyObject is Window)
                {
                    result = dependencyObject.FormatForTextId(true);
                }
                else
                {
                    DependencyObject parent = dependencyObject is Visual || dependencyObject is Visual3D?VisualTreeHelper.GetParent(dependencyObject) : LogicalTreeHelper.GetParent(dependencyObject);

                    result = GetContextByName(parent);
                }
            }

            return(string.IsNullOrEmpty(result) ? dependencyObject?.FormatForTextId(true) ?? string.Empty : result);
        }
예제 #22
0
        /// <summary>
        /// Tries to get a value that is stored somewhere in the visual tree above this <see cref="DependencyObject"/>.
        /// <para>If this is not available, it will register a <see cref="ParentChangedNotifier"/> on the last element.</para>
        /// </summary>
        /// <typeparam name="T">The return type.</typeparam>
        /// <param name="target">The <see cref="DependencyObject"/>.</param>
        /// <param name="GetFunction">The function that gets the value from a <see cref="DependencyObject"/>.</param>
        /// <param name="ParentChangedAction">The notification action on the change event of the Parent property.</param>
        /// <param name="parentNotifiers">A dictionary of already registered notifiers.</param>
        /// <returns>The value, if possible.</returns>
        public static T GetValueOrRegisterParentNotifier <T>(this DependencyObject target, Func <DependencyObject, T> GetFunction, Action <DependencyObject> ParentChangedAction, Dictionary <DependencyObject, ParentChangedNotifier> parentNotifiers)
        {
            var ret = default(T);

            if (target != null)
            {
                var depObj = target;

                while (ret == null)
                {
                    // Try to get the value using the provided GetFunction.
                    ret = GetFunction(depObj);

                    if (ret != null && parentNotifiers.ContainsKey(target))
                    {
                        var notifier = parentNotifiers[target];
                        notifier.Dispose();
                        parentNotifiers.Remove(target);
                    }

                    // Try to get the parent using the visual tree helper. This may fail on some occations.
#if !SILVERLIGHT
                    if (!(depObj is Visual) && !(depObj is Visual3D) && !(depObj is FrameworkContentElement))
                    {
                        break;
                    }

                    if (depObj is Window)
                    {
                        break;
                    }
#endif
                    DependencyObject depObjParent = null;

#if !SILVERLIGHT
                    if (depObj is FrameworkContentElement)
                    {
                        depObjParent = ((FrameworkContentElement)depObj).Parent;
                    }
                    else
                    {
                        try { depObjParent = LogicalTreeHelper.GetParent(depObj); }
                        catch { depObjParent = null; }
                    }
#endif

                    if (depObjParent == null)
                    {
                        try { depObjParent = VisualTreeHelper.GetParent(depObj); }
                        catch { break; }
                    }

                    // If this failed, try again using the Parent property (sometimes this is not covered by the VisualTreeHelper class :-P.
                    if (depObjParent == null && depObj is FrameworkElement)
                    {
                        depObjParent = ((FrameworkElement)depObj).Parent;
                    }

                    if (ret == null && depObjParent == null)
                    {
                        // Try to establish a notification on changes of the Parent property of dp.
                        if (depObj is FrameworkElement && !parentNotifiers.ContainsKey(target))
                        {
                            parentNotifiers.Add(target, new ParentChangedNotifier((FrameworkElement)depObj, () =>
                            {
                                // Call the action...
                                ParentChangedAction(target);
                                // ...and remove the notifier - it will probably not be used again.
                                if (parentNotifiers.ContainsKey(target))
                                {
                                    var notifier = parentNotifiers[target];
                                    notifier.Dispose();
                                    parentNotifiers.Remove(target);
                                }
                            }));
                        }
                        break;
                    }

                    // Assign the parent to the current DependencyObject and start the next iteration.
                    depObj = depObjParent;
                }
            }

            return(ret);
        }
        private void UserControl_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            DependencyObject ucParent = this.Parent;

            while (!(ucParent is UserControl))
            {
                ucParent = LogicalTreeHelper.GetParent(ucParent);
            }

            parentWind = (flightMng)ucParent;

            if (this.Visibility == Visibility.Visible)
            {
                lstCB = FlightMngController.LoadFlightData();
                cmbMaCB.ItemsSource        = lstCB;
                cmbSBTrungGian.ItemsSource = FlightMngController.LoadAirportData();

                if (parentWind.IsSheduleEdit == true)
                {// Xem - sữa
                    lblScheTitle.Content = "CHI TIẾT LỊCH BAY";

                    selected   = FlightMngController.getLBByID(GlobalItem.FlightOfSelectedShedule, GlobalItem.DateOfSelectedShedule);
                    selectedCB = FlightMngController.getCBByID(GlobalItem.FlightOfSelectedShedule);



                    cmbMaCB.IsEnabled    = false;
                    txtSBDi.IsEnabled    = false;
                    txtSBDen.IsEnabled   = false;
                    dp_ngaybay.IsEnabled = false;

                    txtNormalSeats.IsEnabled = false;
                    txtVIPSeats.IsEnabled    = false;

                    int index = GlobalItem.FlightOfSelectedShedule - 1;
                    cmbMaCB.SelectedItem = selectedCB;
                    txtSBDi.Text         = selectedCB.SBDi;
                    txtSBDen.Text        = selectedCB.SBDen;
                    txtDefaultHrs.Text   = selectedCB.ThoiGianBay.Value.Hours.ToString();
                    txtDefaultMins.Text  = selectedCB.ThoiGianBay.Value.Minutes.ToString();

                    txtMins.Text            = selected.GioDi.Value.Minutes.ToString();
                    txtHrs.Text             = selected.GioDi.Value.Hours.ToString();
                    dp_ngaybay.SelectedDate = selected.NgayDi;

                    txtNormalSeats.Text = selected.SoGheThuong.ToString();
                    txtVIPSeats.Text    = selected.SoGheVip.ToString();

                    FlightMngController.loadSBTGList(selected.MaCB, selected.NgayDi, ref lstSBTG, ref lstNote, ref lstStop);
                    listView_SBTG.ItemsSource = lstSBTG;

                    AddCombo.Visibility  = Visibility.Hidden;
                    EditCombo.Visibility = Visibility.Visible;
                    SeatCombo.Visibility = Visibility.Visible;
                }
                else
                {// Them mới
                    lblScheTitle.Content = "THÊM MỚI LỊCH BAY";

                    cmbMaCB.SelectedIndex = 0;
                    txtSBDen.IsEnabled    = false;
                    txtSBDi.IsEnabled     = false;
                    txtSBDi.Text          = lstCB.ElementAt(0).SBDi;
                    txtSBDen.Text         = lstCB.ElementAt(0).SBDen;
                    txtDefaultHrs.Text    = lstCB.ElementAt(0).ThoiGianBay.Value.Hours.ToString();
                    txtDefaultMins.Text   = lstCB.ElementAt(0).ThoiGianBay.Value.Minutes.ToString();

                    AddCombo.Visibility  = Visibility.Visible;
                    EditCombo.Visibility = Visibility.Hidden;
                    SeatCombo.Visibility = Visibility.Hidden;
                }
            }
            else
            {
                cmbMaCB.IsEnabled    = true;
                txtSBDi.IsEnabled    = true;
                txtSBDen.IsEnabled   = true;
                dp_ngaybay.IsEnabled = true;



                parentWind.loadLichBayData();
            }
        }
        // Token: 0x060075FB RID: 30203 RVA: 0x0021A3F0 File Offset: 0x002185F0
        internal override object GetObject(DependencyObject d, ObjectRefArgs args)
        {
            if (d == null)
            {
                throw new ArgumentNullException("d");
            }
            object obj = null;

            if (args.ResolveNamesInTemplate)
            {
                FrameworkElement frameworkElement = d as FrameworkElement;
                if (frameworkElement != null && frameworkElement.TemplateInternal != null)
                {
                    obj = Helper.FindNameInTemplate(this._name, d);
                    if (args.IsTracing)
                    {
                        TraceData.Trace(TraceEventType.Warning, TraceData.ElementNameQueryTemplate(new object[]
                        {
                            this._name,
                            TraceData.Identify(d)
                        }));
                    }
                }
                if (obj == null)
                {
                    args.NameResolvedInOuterScope = true;
                }
            }
            FrameworkObject frameworkObject = new FrameworkObject(d);

            while (obj == null && frameworkObject.DO != null)
            {
                DependencyObject dependencyObject;
                obj = frameworkObject.FindName(this._name, out dependencyObject);
                if (d == dependencyObject && d is IComponentConnector && d.ReadLocalValue(NavigationService.NavigationServiceProperty) == DependencyProperty.UnsetValue)
                {
                    DependencyObject dependencyObject2 = LogicalTreeHelper.GetParent(d);
                    if (dependencyObject2 == null)
                    {
                        dependencyObject2 = Helper.FindMentor(d.InheritanceContext);
                    }
                    if (dependencyObject2 != null)
                    {
                        obj = null;
                        frameworkObject.Reset(dependencyObject2);
                        continue;
                    }
                }
                if (args.IsTracing)
                {
                    TraceData.Trace(TraceEventType.Warning, TraceData.ElementNameQuery(new object[]
                    {
                        this._name,
                        TraceData.Identify(frameworkObject.DO)
                    }));
                }
                if (obj == null)
                {
                    args.NameResolvedInOuterScope = true;
                    FrameworkObject  frameworkObject2  = new FrameworkObject(dependencyObject);
                    DependencyObject dependencyObject3 = frameworkObject2.TemplatedParent;
                    if (dependencyObject3 == null)
                    {
                        Panel panel = frameworkObject.FrameworkParent.DO as Panel;
                        if (panel != null && panel.IsItemsHost)
                        {
                            dependencyObject3 = panel;
                        }
                    }
                    if (dependencyObject3 == null && dependencyObject == null)
                    {
                        ContentControl contentControl = LogicalTreeHelper.GetParent(frameworkObject.DO) as ContentControl;
                        if (contentControl != null && contentControl.Content == frameworkObject.DO && contentControl.InheritanceBehavior == InheritanceBehavior.Default)
                        {
                            dependencyObject3 = contentControl;
                        }
                    }
                    if (dependencyObject3 == null && dependencyObject == null)
                    {
                        dependencyObject3 = frameworkObject.DO;
                        for (;;)
                        {
                            DependencyObject dependencyObject4 = LogicalTreeHelper.GetParent(dependencyObject3);
                            if (dependencyObject4 == null)
                            {
                                dependencyObject4 = Helper.FindMentor(dependencyObject3.InheritanceContext);
                            }
                            if (dependencyObject4 == null)
                            {
                                break;
                            }
                            dependencyObject3 = dependencyObject4;
                        }
                        ContentPresenter contentPresenter = VisualTreeHelper.IsVisualType(dependencyObject3) ? (VisualTreeHelper.GetParent(dependencyObject3) as ContentPresenter) : null;
                        dependencyObject3 = ((contentPresenter != null && contentPresenter.TemplateInternal.CanBuildVisualTree) ? contentPresenter : null);
                    }
                    frameworkObject.Reset(dependencyObject3);
                }
            }
            if (obj == null)
            {
                obj = DependencyProperty.UnsetValue;
                args.NameResolvedInOuterScope = false;
            }
            return(obj);
        }
예제 #25
0
        public static DependencyObject FindVisualTreeRoot(this DependencyObject initial)
        {
            DependencyObject dependencyObject1 = initial;
            DependencyObject dependencyObject2 = initial;

            for (; dependencyObject1 != null; dependencyObject1 = dependencyObject1 is Visual || dependencyObject1 is Visual3D ? VisualTreeHelper.GetParent(dependencyObject1) : LogicalTreeHelper.GetParent(dependencyObject1))
            {
                dependencyObject2 = dependencyObject1;
            }
            return(dependencyObject2);
        }
예제 #26
0
        private void UserControl_Loaded(object sender, RoutedEventArgs ea)
        {
            DependencyObject ucParent = (sender as DayScheduler).Parent;

            while (!(ucParent is Scheduler))
            {
                ucParent = LogicalTreeHelper.GetParent(ucParent);
            }

            _scheduler = ucParent as Scheduler;

            _scheduler.OnEventAdded += ((object s, Event e) =>
            {
                if (e.Start.Date == e.End.Date)
                {
                    PaintAllEvents();
                }
                else
                {
                    PaintAllDayEvents();
                }
            });

            _scheduler.OnEventDeleted += ((object s, Event e) =>
            {
                if (e.Start.Date == e.End.Date)
                {
                    PaintAllEvents();
                }
                else
                {
                    PaintAllDayEvents();
                }
            });

            _scheduler.OnEventsModified += ((object s, EventArgs e) =>
            {
                PaintAllEvents();
                PaintAllDayEvents();
            });

            _scheduler.OnStartJourneyChanged += ((object s, TimeSpan t) =>
            {
                if (_scheduler.StartJourney.Hours == 0)
                {
                    startJourney.Visibility = System.Windows.Visibility.Hidden;
                }
                else
                {
                    Grid.SetRowSpan(startJourney, (int)t.TotalHours * 2);
                }
            });

            _scheduler.OnEndJourneyChanged += ((object s, TimeSpan t) =>
            {
                if (_scheduler.EndJourney.Hours == 0)
                {
                    endJourney.Visibility = System.Windows.Visibility.Hidden;
                }
                else
                {
                    Grid.SetRow(endJourney, (int)t.Hours);
                    Grid.SetRowSpan(endJourney, 48 - (int)t.Hours * 2);
                }
            });

            (sender as DayScheduler).SizeChanged += DayScheduler_SizeChanged;

            ResizeGrids(new Size(this.ActualWidth, this.ActualHeight));
            PaintAllEvents();
            PaintAllDayEvents();
            if (_scheduler.StartJourney.Hours != 0)
            {
                double hourHeight = EventsGrid.ActualHeight / 22;
                ScrollEventsViewer.ScrollToVerticalOffset(hourHeight * (_scheduler.StartJourney.Hours - 1));
            }

            if (_scheduler.StartJourney.Hours == 0)
            {
                startJourney.Visibility = System.Windows.Visibility.Hidden;
            }
            else
            {
                Grid.SetRowSpan(startJourney, _scheduler.StartJourney.Hours * 2);
            }

            if (_scheduler.EndJourney.Hours == 0)
            {
                endJourney.Visibility = System.Windows.Visibility.Hidden;
            }
            else
            {
                Grid.SetRow(endJourney, _scheduler.EndJourney.Hours * 2);
                Grid.SetRowSpan(endJourney, 48 - _scheduler.EndJourney.Hours * 2);
            }
        }
예제 #27
0
 public static DependencyObject GetParent(this DependencyObject obj)
 {
     return(obj is System.Windows.Media.Visual ? VisualTreeHelper.GetParent(obj) : LogicalTreeHelper.GetParent(obj));
 }
예제 #28
0
        public void ChangeSelection(object item, MyRibbonGalleryItem container, bool isSelected)
        {
            if (this.IsSelectionChangeActive)
            {
                return;
            }
            object selectedItem = this.SelectedItem;
            object itemValue    = item;
            bool   flag         = !MyRibbonGallery.VerifyEqual(selectedItem, itemValue);

            try
            {
                Debug.WriteLine("here");
                this.IsSelectionChangeActive = true;
                if (isSelected == flag)
                {
                    Debug.WriteLine("here1");
                    if (!isSelected && container != null)
                    {
                        Debug.WriteLine("here2");
                        container.IsSelected = false;
                        int index = this._selectedContainers.IndexOf(container);
                        if (index > -1)
                        {
                            Debug.WriteLine("here3");
                            this._selectedContainers.RemoveAt(index);
                            container.OnUnselected_(new RoutedEventArgs(RibbonGalleryItem.UnselectedEvent, (object)container));
                        }
                    }
                    else
                    {
                        Debug.WriteLine("here4");
                        for (int index = 0; index < this._selectedContainers.Count; ++index)
                        {
                            MyRibbonGalleryItem selectedContainer = (MyRibbonGalleryItem)this._selectedContainers[index];
                            selectedContainer.IsSelected = false;
                            selectedContainer.OnUnselected_(new RoutedEventArgs(RibbonGalleryItem.UnselectedEvent, (object)selectedContainer));
                            if (!isSelected)
                            {
                                Debug.WriteLine("here5");
                                this.MoveCurrentToPosition_(selectedContainer.RibbonGalleryCategory.CollectionView, -1);
                            }
                        }
                        this._selectedContainers.Clear();
                        if (!isSelected)
                        {
                            Debug.WriteLine("here6");
                            this.InvalidateProperty(RibbonGallery.SelectedItemProperty);
                            this.InvalidateProperty(RibbonGallery.SelectedValueProperty);
                            this.MoveCurrentToPosition_(this.CollectionView, -1);
                            this.MoveCurrentToPosition_(this.SourceCollectionView, -1);
                            if (LogicalTreeHelper.GetParent((DependencyObject)this) is MyRibbonComboBox parent && this == parent.FirstGallery && !parent.IsSelectedItemCached)
                            {
                                parent.UpdateSelectionProperties_();
                            }
                        }
                    }
                    if (isSelected)
                    {
                        Debug.WriteLine("here7");
                        this.SetCurrentValue(RibbonGallery.SelectedItemProperty, item);
                        this.SetCurrentValue(RibbonGallery.SelectedValueProperty, this.GetSelectableValueFromItem(item));
                        if (container != null)
                        {
                            this.SynchronizeWithCurrentItem(container.RibbonGalleryCategory, item);
                        }
                        else
                        {
                            this.SynchronizeWithCurrentItem();
                        }
                    }
                }
                if (isSelected)
                {
                    Debug.WriteLine("here8");
                    if (container != null)
                    {
                        Debug.WriteLine("here9");
                        if (!this._selectedContainers.Contains(container))
                        {
                            Debug.WriteLine("her10e");
                            this._selectedContainers.Add(container);
                            container.IsSelected = true;
                            container.OnSelected_(new RoutedEventArgs(RibbonGalleryItem.SelectedEvent, (object)container));
                        }
                    }
                }
            }
            finally
            {
                this.IsSelectionChangeActive = false;
            }

            if (!flag)
            {
                Debug.WriteLine("here11");
                return;
            }

            Debug.WriteLine("here12");
            this.OnSelectionChanged(new RoutedPropertyChangedEventArgs <object>(selectedItem, isSelected ? itemValue : (object)null, RibbonGallery.SelectionChangedEvent));
        }
예제 #29
0
        /// <summary>
        /// Shows a custom control as a tooltip in the tray location.
        /// </summary>
        /// <param name="balloon"></param>
        /// <param name="animation">An optional animation for the popup.</param>
        /// <param name="timeout">The time after which the popup is being closed.
        /// Submit null in order to keep the balloon open inde
        /// </param>
        /// <exception cref="ArgumentNullException">If <paramref name="balloon"/>
        /// is a null reference.</exception>
        public void ShowCustomBalloon(UIElement balloon, PopupAnimation animation, int?timeout)
        {
            Dispatcher dispatcher = this.GetDispatcher();

            if (!dispatcher.CheckAccess())
            {
                var action = new Action(() => ShowCustomBalloon(balloon, animation, timeout));
                dispatcher.Invoke(DispatcherPriority.Normal, action);
                return;
            }

            if (balloon == null)
            {
                throw new ArgumentNullException("balloon");
            }
            if (timeout.HasValue && timeout < 500)
            {
                string msg = "Invalid timeout of {0} milliseconds. Timeout must be at least 500 ms";
                msg = String.Format(msg, timeout);
                throw new ArgumentOutOfRangeException("timeout", msg);
            }

            EnsureNotDisposed();

            //make sure we don't have an open balloon
            lock (this)
            {
                CloseBalloon();
            }

            //create an invisible popup that hosts the UIElement
            Popup popup = new Popup();

            popup.AllowsTransparency = true;

            //provide the popup with the taskbar icon's data context
            UpdateDataContext(popup, null, DataContext);

            //don't animate by default - devs can use attached
            //events or override
            popup.PopupAnimation = animation;

            //in case the balloon is cleaned up through routed events, the
            //control didn't remove the balloon from its parent popup when
            //if was closed the last time - just make sure it doesn't have
            //a parent that is a popup
            var parent = LogicalTreeHelper.GetParent(balloon) as Popup;

            if (parent != null)
            {
                parent.Child = null;
            }

            if (parent != null)
            {
                string msg =
                    "Cannot display control [{0}] in a new balloon popup - that control already has a parent. You may consider creating new balloons every time you want to show one.";
                msg = String.Format(msg, balloon);
                throw new InvalidOperationException(msg);
            }

            popup.Child = balloon;

            //don't set the PlacementTarget as it causes the popup to become hidden if the
            //TaskbarIcon's parent is hidden, too...
            //popup.PlacementTarget = this;

            popup.Placement = PlacementMode.AbsolutePoint;
            popup.StaysOpen = true;

            Point position = TrayInfo.GetTrayLocation();

            position = GetDeviceCoordinates(position);
            popup.HorizontalOffset = position.X - 1;
            popup.VerticalOffset   = position.Y - 1;

            //store reference
            lock (this)
            {
                SetCustomBalloon(popup);
            }

            //assign this instance as an attached property
            SetParentTaskbarIcon(balloon, this);

            //fire attached event
            RaiseBalloonShowingEvent(balloon, this);

            //display item
            popup.IsOpen = true;

            if (timeout.HasValue)
            {
                //register timer to close the popup
                balloonCloseTimer.Change(timeout.Value, Timeout.Infinite);
            }
        }
        // Token: 0x06002CC1 RID: 11457 RVA: 0x000C9D38 File Offset: 0x000C7F38
        internal ContentPosition GetObjectPosition(object o)
        {
            if (o == null)
            {
                throw new ArgumentNullException("o");
            }
            DependencyObject dependencyObject = o as DependencyObject;

            if (dependencyObject == null)
            {
                throw new ArgumentException(SR.Get("FixedDocumentExpectsDependencyObject"));
            }
            FixedPage fixedPage = null;
            int       num       = -1;

            if (dependencyObject != this)
            {
                DependencyObject dependencyObject2 = dependencyObject;
                while (dependencyObject2 != null)
                {
                    fixedPage = (dependencyObject2 as FixedPage);
                    if (fixedPage != null)
                    {
                        num = this.GetIndexOfPage(fixedPage);
                        if (num >= 0)
                        {
                            break;
                        }
                        dependencyObject2 = fixedPage.Parent;
                    }
                    else
                    {
                        dependencyObject2 = LogicalTreeHelper.GetParent(dependencyObject2);
                    }
                }
            }
            else if (this.Pages.Count > 0)
            {
                num = 0;
            }
            FixedTextPointer fixedTextPointer = null;

            if (num >= 0)
            {
                FlowPosition flowPosition       = null;
                System.Windows.Shapes.Path path = dependencyObject as System.Windows.Shapes.Path;
                if (dependencyObject is Glyphs || dependencyObject is Image || (path != null && path.Fill is ImageBrush))
                {
                    FixedPosition fixedPosition = new FixedPosition(fixedPage.CreateFixedNode(num, (UIElement)dependencyObject), 0);
                    flowPosition = this.FixedContainer.FixedTextBuilder.CreateFlowPosition(fixedPosition);
                }
                if (flowPosition == null)
                {
                    flowPosition = this.FixedContainer.FixedTextBuilder.GetPageStartFlowPosition(num);
                }
                fixedTextPointer = new FixedTextPointer(true, LogicalDirection.Forward, flowPosition);
            }
            if (fixedTextPointer == null)
            {
                return(ContentPosition.Missing);
            }
            return(fixedTextPointer);
        }