I want to create a WPF element that, at runtime, has full control over its children - adding and removing a child interface when its properties change. Something is a bit like what an ItemsControl does when the ItemsSource property changes, although in my case there will be only one child.
This will be the view container for MVVM - when you give it a model or ViewModel, it will magically create the correct view and connect everything. There, it is not necessary that my view container be templatable (as it creates user views that are UserControls and have their own templates), and I would prefer it to encapsulate as much as possible. I could probably do this easily by going down from something like a Grid and adding child controls when my own properties change; but Grid publicly provides its collection of children and allows you to add and remove things.
What WPF class should be omitted for maximum encapsulation and how to add children to it at runtime?
Based on my understanding of the docs, I tried using FrameworkElement and AddVisualChild to check if I can create child controls at runtime. I donβt understand if AddLogicalChild is needed, but I put it on just in case:
public class ViewContainer : FrameworkElement { private TextBlock _child; public ViewContainer() { _child = new TextBlock { Text = "ViewContainer" }; AddLogicalChild(_child); AddVisualChild(_child); InvalidateMeasure(); } public object Content { get; set; } protected override Size ArrangeOverride(Size finalSize) { _child.Arrange(new Rect(finalSize)); return finalSize; } protected override Size MeasureOverride(Size availableSize) { _child.Measure(availableSize); return _child.DesiredSize; } }
When I put the ViewContainer in the window and run it, I expect to see a TextBlock with the words "ViewContainer". But instead, I just see an empty window. Therefore, obviously, I missed something.
How can I fix the above code so that the "child" control is displayed at runtime but not open to others that could be interacted with (moreover, which can be avoided)?
source share