The problem is that you never use your
VisualCollection
, only create it. How do you think the rest of your application can "know" that this collection even exist?
You don't even need this fictional "Loaded" event; you can call the code adding visuals from the constructor directly. For example, the rendering you tried to create in your code sample can be done this way:
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
visuals = new VisualCollection(this);
DrawIt();
}
VisualCollection visuals;
void DrawIt() {
DrawingVisual visual = new DrawingVisual();
using (DrawingContext dc = visual.RenderOpen()) {
dc.DrawRectangle(
Brushes.Red, new Pen(Brushes.Red, 5),
new Rect(10, 10, 100, 100));
}
visuals.Add(visual);
}
protected override Visual GetVisualChild(int index) {
return visuals[index];
}
protected override int VisualChildrenCount {
get { return visuals.Count; }
}
}
Can you spot the difference? :-)
But I would not advise drawing on the Window directly. Instead, create some custom
UIElement
(derived class) using the visuals in exact same way, and add it the the window's
logical tree, as any other
UIElement
(to a grid or other container, or a window itself), directly or using XAML. Please see the complete sample in this tutorial:
https://tarundotnet.wordpress.com/2011/05/19/wpf-tutorial-drawing-visual[
^].
I tried it out, it works.
—SA