0

如何获取画布的元素?

我有这个:

<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 对象,但是画布对象正在各种类中被绘制,如果它已经是,我不想将矩形传递给每个类包含在画布中。

4

1 回答 1

9

你可以试试这个:

// 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<>()因为它检查类型并且仅在类型正确时才生成项目。(已经投了)

于 2013-10-12T21:40:20.533 回答