开发者

Canvas in WPF - How do I detect when an element has been added/removed from the canvas?

I created my own subclass from the standard WPF canvas to support various additional functions, amongst those I wanted to manage the Z-Index of the elements on the canvas, but in order to do that I need to run some code whenever an element is added or removed to/from the canvas. Unfortunately not the canvas nor it Children property seem to have appropriate events to handle these cases.

What would be the best/simplest way to fix this? Right now I call a method manually from the outside from wherever in my code I'm adding/removing something, but that's quite "hacky" and 开发者_如何学Pythonnot very nice for future reuse of the code.


Check this post on MSDN, I think it answers your question.

As for your problem, I think you can try to override the OnVisualChildrenChanged() when the child is added, it can resolve your issue, more details you can refer to: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/d8933264-0958-499f-b6cd-41d61713ac8e


I think the best way is to override the ArrangeOverride of the Canvas class as you are in fact changing the arrangement of the children.

You could keep a history of the previous child collection and compare it with the current.

EDIT mzabsky is right you should try to use OnVisualChildrenChanged first.


I can't add comment. So, I want add information in previous comment. Of course In my example I can't use OnVisualChildrenChanged or ArrangeOverride.

I have cach list with previous children:

private readonly List<UIElement> _elements = new List<UIElement>();

I subscribe event, which call, when any property changed - LayoutUpdated. In Event handler:

        if (_canvas == null) return;
        var children = _canvas.Children.OfType<UIElement>().ToList();
        if (_elements.SequenceEqual(children)) return;
        var removeElements = _elements.Except(children);
        var newelements = children.Except(_elements);
        _elements.AddRange(newelements);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜