Canvas in WPF - How to determine when an item has been added / removed from the canvas?

I created my own subclass from the standard WPF canvas to support various additional functions, among which I wanted to control the Z-index of elements on the canvas, but for this I need to run some code whenever an element is added or removed to / from the canvas. Unfortunately, not for the canvas, but for the "Children" property, there seem to be relevant events to handle these cases.

What would be the best / easiest way to fix this? Right now I am calling the method manually from the outside, no matter where in my code, I am adding / removing something, but it is rather “hacked” and not very pleasant for subsequent code reuse.

+4
source share
3 answers

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

As for your problem, I think you can try to override OnVisualChildrenChanged (), when the child is added, he can solve your problem, you can get more detailed information at the link: http://social.msdn.microsoft.com/Forums/en -US / wpf / thread / d8933264-0958-499f-b6cd-41d61713ac8e

+5
source

I think the best way is to override the Canvas class's ArrangeOverride , since you are actually changing the layout of the children.

You can save the history of the previous child collection and compare it with the current one.

EDIT mzabsky is right, you should first try using OnVisualChildrenChanged first.

0
source

I can not add a comment. So, I want to add information to the previous comment. Of course, in my example, I cannot use OnVisualChildrenChanged or ArrangeOverride.

I have a cach list with previous children:

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

I am signing an event that fires when a property is changed - LayoutUpdated. In the 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
source

All Articles