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 Add开发者_如何学PythonLogicalChild(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?
If working only with UIElement
s, the prefered way is to add that items to the Children
collection.
But if you have a mixture of UIElement
s and Visual
s, I would suggest to use the methods AddLogicalChild
/ AddVisualChild
instead of Children
. However, that requires a little bit more work:
- Add the item (
Visual
s as well asUIElement
s) as logical and visual children, usingAddLogicalChild
andAddVisualChild
. - Store the items somewhere (the Panel wont do it for you)
- Overwrite
GetVisualChild
andVisualChildrenCount
and return the number of items / the item on the passed index - Overwrite MeasureOverride, call
UIElement.Measure
on eachUIElement
and do all the other measure stuff that is specific for your panel - Overwrite ArrangeOverride, call
UIElement.Arrange
for eachUIElement
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. :)
For UIElement
s, it's the Collection Children
to use:
public void AddChild(UIElement newChild)
{
this.Children.Add(newChild);
}
You should also look at the InternalChildren Collection which is recommanded to use in extensions of Panel
s.
That functionality is already included. If you want to add UIElements
to your Panel
, simply use .Children.Add()
- just like you do with the regular Canvas
, Grid
etc.
Then in your implementation, override MeasureOverride
and ArrangeOverride
to iterate through the children and organize them on your Panel
surface.
Example here: http://msdn.microsoft.com/en-us/library/ms754152(v=vs.110).aspx#Panels_custom_panel_elements
精彩评论