Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding UIElement with AddLogicalChild, AddVisualChild in WPF

I created a custom version of canvas by simply extending/inheriting from the Panel.

When I want to draw or render something on it, I simply create a DrawingVisual, draw the desired graphics and call the AddLogicalChild(Visual), AddVisualChild(Visual) and incrementing the count of the Visuals of the Panel.

This works great when I am adding DrawingVisual instances, but when I try to add a Button here and define the dimensions (MinHeight, MinWidth), it is not displayed.

Is it possible that UIElements need a different logic of handling to be displayed? Basically, how can I add a UIElement to that extended Panel that would be displayed and could be manipulated with?

like image 490
grizzly Avatar asked Oct 31 '25 05:10

grizzly


1 Answers

If working only with UIElements, the prefered way is to add that items to the Children collection.

But if you have a mixture of UIElements and Visuals, I would suggest to use the methods AddLogicalChild / AddVisualChild instead of Children. However, that requires a little bit more work:

  1. Add the item (Visuals as well as UIElements) as logical and visual children, using AddLogicalChild and AddVisualChild.
  2. Store the items somewhere (the Panel wont do it for you)
  3. Overwrite GetVisualChild and VisualChildrenCount and return the number of items / the item on the passed index
  4. Overwrite MeasureOverride, call UIElement.Measure on each UIElement and do all the other measure stuff that is specific for your panel
  5. Overwrite ArrangeOverride, call UIElement.Arrange for each UIElement and do all the other arrange stuff that is specific for your panel

Note that Measure and Arrange have to be called after the UIElement has been added to the Panel.

Thats it. :)

like image 53
JanDotNet Avatar answered Nov 03 '25 23:11

JanDotNet