user90150
user90150

Reputation:

WPF Event to capture newly added controls?

We use the ContentControl and other containers stuff in WPF. I need the notification with the new child control is added to the container. What is the best way to get the newly created control within parent?

Upvotes: 4

Views: 1366

Answers (2)

Rick Sladkey
Rick Sladkey

Reputation: 34250

The cleanest way is to derive from those control and override the methods that report the changes you are interested in. For example derive from ContentControl and implement OnContentChanged. This approach may not appeal to you.

If you want to detect changes in the child or children of controls without deriving from them, you can observe that such changes will affect the layout and so you can hook the LayoutUpdated event. The problem with this approach is that you need to keep track of the children that were previously added yourself by inspecting Child or Children looking for changes. You also have to be careful not to hang onto references to former children lest you create a memory leak. But it can be done.

Upvotes: 1

Phil Wright
Phil Wright

Reputation: 22956

The ContentControl only contains a single child which is attached via the ContentControl.Content property. You can hook the ContentControl.OnContentChanged to discover when the value of this property is updated.

Upvotes: 3

Related Questions