如何在附加属性中初始化装饰器

时间:2011-03-17 03:44:20

标签: wpf .net-4.0

我想在附加属性中为Adorner创建FrameworkElement。但在PropertyChangedCallback AdornerLayer中我的元素是null

我该如何解决这个问题?

目前我这样做:

    private static void _OnIsModalAdornerAttachedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var element = d as FrameworkElement;

        bool oldValue = (bool)e.OldValue;
        bool newValue = (bool)e.NewValue;

        if (null != element && oldValue != newValue)
        {
            var descriptor = DependencyPropertyDescriptor.FromProperty(VisibilityProperty, typeof(FrameworkElement));

            if (newValue)
            {
                descriptor.AddValueChanged(element, element_VisibilityChanged);
            }
            else
            {
                descriptor.RemoveValueChanged(element, element_VisibilityChanged);
            }
    }


private static void element_VisibilityChanged(object sender, EventArgs e)
        {
            var element = sender as FrameworkElement;

            if (null != element)
            {
                var adornerLayer = AdornerLayer.GetAdornerLayer(element);

                if (null != adornerLayer)
                {
                    // check if adorner exists
                    bool isExists = false;
                    var adorners = adornerLayer.GetAdorners(element);
                    if (null != adorners)
                    {
                        foreach (var adorner in adorners)
                        {
                            if (adorner is ModalAdorner)
                            {
                                isExists = true;
                                break;
                            }
                        }
                    }

                    // add if is not presented
                    if (!isExists)
                    {
                        var modalAdorner = new ModalAdorner(element);
                        adornerLayer.Add(modalAdorner);

                        var visibilityBinding = new Binding { Path = new PropertyPath("Visibility"), Source = element };
                        modalAdorner.SetBinding(VisibilityProperty, visibilityBinding);
                    }
                }
            }
        }

然后,我手动将Visibility的{​​{1}}属性更改为FrameworkElement,然后再更改为Hidden。但这种方式并非如此。

更新

我解决了这个问题。现在我这样做:

Visible

1 个答案:

答案 0 :(得分:1)

答案是更新:使用Loaded事件。