Ejemplo n.º 1
0
        private static void IsKeyboardFocusWithinAnchorChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            var element = sender as FrameworkElement;

            if (element == null || DesignerProperties.GetIsInDesignMode(element))
            {
                return;
            }

            //如果元素内部还包含该装饰器,为防止重叠,则不处理
            if (element.FirstVisualTreeChildren(x => AnchorAdorner.GetIsKeyboardFocusWithinAnchor(x)) != null)
            {
                return;
            }
            var flag = (bool)e.NewValue;

            element.Dispatcher.BeginInvoke(new Action(() =>
            {
                //安装或卸载装饰器
                var anchor = AnchorAdorner.GetKeyboardWithinAnchor(element);
                //若flag为false,且anchor不存在,则直接退出
                if (anchor == null && !flag)
                {
                    return;
                }
                var adornerLayer = AdornerLayer.GetAdornerLayer(element);
                if (adornerLayer == null)
                {
                    return;
                }
                if (anchor == null)
                {
                    anchor = new AnchorAdorner(element);
                    AnchorAdorner.SetKeyboardWithinAnchor(element, anchor);
                    //装饰器Visibility与依附元素的IsVisible绑定
                    anchor.SetBinding(FrameworkElement.VisibilityProperty,
                                      new System.Windows.Data.Binding()
                    {
                        Source    = element,
                        Converter = ValueConverter.BoolToVisibility,
                        Path      = new PropertyPath(IsVisibleProperty)
                    });
                }
                adornerLayer.Remove(anchor);
                if (flag)
                {
                    adornerLayer.Add(anchor);
                }
            }), System.Windows.Threading.DispatcherPriority.Loaded);
        }
Ejemplo n.º 2
0
 private static void SetKeyboardWithinAnchor(DependencyObject obj, AnchorAdorner value)
 {
     obj.SetValue(KeyboardWithinAnchorProperty, value);
 }