wpf 如何获取画布的元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19338071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get the elements of a canvas?
提问by William
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:
如您所见,在 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");
}
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 对象,但是画布对象正在被绘制到不同的类中,如果它已经是,我不想将矩形传递给每个类包含在画布中。
回答by Jeroen van Langen
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)
的OfType<>(),因为它会检查类型,如果它是正确的类型只产生一个项目是非常有用的。(已经投过了)

