我怎样才能获得画布的元素?

时间:2013-10-12 19:07:17

标签: c# wpf xaml object canvas

如何获取画布的元素?

我有这个:

<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>

正如您所看到的,XAML代码中的这个画布上有一些对象。我需要获取Rectangle对象的详细信息:

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");
}

我知道我可能只是通过在XAML中给它一个变量名来访问Rectangle对象,但是canvas对象是在各种类中绘制的,我不希望将矩形传递给每个类。它已经包含在画布中。

1 个答案:

答案 0 :(得分:7)

你可以试试这个:

// 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");

OfType<>()非常有用,因为它会检查类型,如果它是正确的类型,则只生成一个项目。 (它已经投入使用)