William
William

Reputation: 1895

How can I get the elements of a canvas?

How can I get the elements of a canvas?

I have this:

<Canvas x:Name="can" HorizontalAlignment="Left" Height="502" Margin="436,0,0,0" VerticalAlignment="Top" Width="336" OpacityMask="#FFC52D2D">
    <Canvas.Background>
        <SolidColorBrush Color="{DynamicResource {x:Static SystemColors.ActiveCaptionColorKey}}"/>
    </Canvas.Background>
    <Button x:Name="btn_twoThreads" Content="Two Threads" Height="32" Canvas.Left="195" Canvas.Top="460" Width="131" Click="btn_twoThreads_Click"/>
    <Button x:Name="btn_oneThread" Content="One Thread" Height="32" Canvas.Left="10" Canvas.Top="460" Width="131" Click="btn_oneThread_Click"/>
    <Rectangle Fill="#FFF4F4F5" Height="55" Canvas.Left="10" Stroke="Black" Canvas.Top="388" Width="316"/>
</Canvas>

As you can see there are some objects on this canvas in the XAML Code. I need to get the the Rectangle object's details:

Rectangle r; 

r = can.Children[2] as Rectangle; //I know this probably doesn't retrieve the rectangle object, but hopefully you can see what I am trying to achieve.

if (r != null)
{
    MessageBox.Show("It's a rectangle");
}

I know I could probably just access the Rectangle object by just giving it a variable name in the XAML, but the canvas object is being drawn to in various classes, and I don't want to pass the rectangle to every class if it is already contained within the canvas.

Upvotes: 1

Views: 6878

Answers (1)

Jeroen van Langen
Jeroen van Langen

Reputation: 22038

You could try this:

// to show that you'll get an enumerable of rectangles.
IEnumerable<Rectangle> rectangles = can.Children.OfType<Rectangle>();

foreach(var rect in rectangles)
{
    // do something with the rectangle
}

Trace.WriteLine("Found " + rectangles.Count() + " rectangles");

The OfType<>() is very useful because it checks the type and only yields an item if it is the right type. (it's casted already)

Upvotes: 10

Related Questions