[英]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. 如您所见,XAML代码中的画布上有一些对象。 I need to get the the Rectangle object's details: 我需要获取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");
}
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. 我知道我可以通过在XAML中给它一个变量名来访问Rectangle对象,但是canvas对象正在各种类中被绘制,并且我不想将矩形传递给每个类(如果已经存在)包含在画布中。
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. OfType<>()
非常有用,因为它会检查类型,并且只有在它是正确的类型时才产生一个项目。 (it's casted already) (已经投放)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.