Question

I started playing around with WPF today, and I ran into some problems concerning drawing of Visuals

I have a class called Prototype.cs, basicly all it does is to draw a visual in the form of an elipse. Nothing tricky here.

class Prototype : FrameworkElement
{
    // A collection of all the visuals we are building.
    VisualCollection theVisuals;

    public Prototype()
    {
        theVisuals = new VisualCollection(this);
        theVisuals.Add(AddCircle());
    }

    private Visual AddCircle()
    {
        DrawingVisual drawingVisual = new DrawingVisual();
        // Retrieve the DrawingContext in order to create new drawing content.
        using (DrawingContext drawingContext = drawingVisual.RenderOpen())
        {
            // Create a circle and draw it in the DrawingContext.
            Rect rect = new Rect(new Point(160, 100), new Size(320, 80));
            drawingContext.DrawEllipse(Brushes.DarkBlue, null, new Point(70, 90), 40, 50);
        }
        return drawingVisual;
    }
}

But this is where I get confused. I'm calling the constructor on this class, through the xaml code, which is very new to me. It works as intended and the elipse is drawn. But I would like to have an instance of my class, that I can use later in my program.

xamlCode

If I remove the xaml code and create an instance of my object by myself, nothing is drawn in my window. Even if I supply MainWindow as parameter as the VisualParent for my VisualCollection it still doesn't work. I would like to keep things sperated, so that I don't need to start creating my visual collection in my MainWindow.cs. I have thought about making a static class to handle all visuals, but isn't there a simpler way to achieve this?

The instantiation of the prototype class:

public MainWindow()
{
    Prototype pt = new Prototype(this);
    InitializeComponent();
}

The prototype constructor:

public Prototype(Visual parent)
{
     theVisuals = new VisualCollection(parent);
     theVisuals.Add(AddCircle());
 }  
Was it helpful?

Solution

You could assign a name to the Prototype instance created in XAML

<Window ...>
    <custom:Prototype x:Name="prototype"/>
</Window>

and then access the instance in code like this:

public MainWindow()
{
    InitializeComponent();
    prototype.DoSomething();
}

Or, you create it in code and assign it to the Wondow's Content property:

public MainWindow()
{
    InitializeComponent();
    var prototype = new Prototype();
    Content = prototype;
    prototype.DoSomething();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top