2013-10-12 60 views
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 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對象,但畫布對象被吸引到各階層,如果它已包含在畫布中,我不想將矩形傳遞給每個類。

+0

'can.Children [2]'會給你矩形。你有任何錯誤或什麼? –

+1

如果我正確地理解了你,你可以隨時把它寫成一個自定義用戶控件,並根據需要公開public按鈕/矩形的getter。特別是如果(從它聽起來像)你在幾個地方使用相似/相同的畫布標記。 –

+0

如果你知道它們是什麼類型,你可以這樣做:http://stackoverflow.com/questions/974598/find-all-controls-in-wpf-window-by-type –

回答

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<>()是非常有用的,因爲它會檢查類型,如果它是正確的類型只產生一個項目。 (它已鑄造)