2011-03-01 69 views
1

在下面的代碼片段中,我在按鈕單擊時添加了新的矩形。 目前他們正在從上到下增加,但我想在底部將它們添加到上的順序向silverlight動態添加矩形控件

<UserControl x:Class="StackImp.MainPage" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d" 
    d:DesignHeight="300" d:DesignWidth="400"> 

    <Canvas x:Name="LayoutRoot" Background="White"> 
     <Canvas x:Name="canvasChild" Background="Red"></Canvas> 
     <Button x:Name="btnPush" Content="Add" Height="20" Width="40" Margin="12,268,348,12" Click="btnPush_Click"></Button> 
     <Button Content="Remove" Height="20" Margin="78,268,282,12" Name="btnPop" Width="40" /> 
    </Canvas> 
</UserControl> 




using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Documents; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Animation; 
using System.Windows.Shapes; 

namespace StackImp 
{ 
    public partial class MainPage : UserControl 
    { 
     StackPanel sp1 = new StackPanel(); 
     public MainPage() 
     { 
      InitializeComponent(); 
      sp1.Orientation = Orientation.Vertical; 
      canvasChild.Children.Add(sp1); 

     } 

     private void btnPush_Click(object sender, RoutedEventArgs e) 
     { 
      Rectangle rect = new Rectangle() 
      { 

       Height = 30, 
       Width = 30, 
       StrokeThickness = 3, 
       Stroke = new SolidColorBrush(Colors.Red), 

      }; 
      sp1.Children.Add(rect); 
     } 
    } 
} 
+0

使用Insert方法,而不是添加使他們獲得加在前面。 – 2011-03-01 08:00:59

+0

@Hans Passant:不起作用 – 2011-03-01 08:30:08

+0

畫布上的所有元素應使用座標明確定位。如果您需要對齊,可能會考慮更適合您需求的不同佈局元素。我不認爲用你現在的佈局是不可能的,但是無論哪種方式,解決方案看起來都會有些不一樣。 – 2011-03-01 09:48:56

回答

2

試試這個。

XAML

C#

private void Button_Click(object sender, RoutedEventArgs e) 
{ 
    Border border = new Border(); 
    border.Height = 50; 
    border.Width = 50; 
    border.BorderBrush = new SolidColorBrush(Colors.Black); 
    border.BorderThickness = new Thickness(2); 
    border.Child = new TextBlock() 
    { 
     Text = sp1.Children.Count.ToString(), 
     HorizontalAlignment = System.Windows.HorizontalAlignment.Center, 
     VerticalAlignment = System.Windows.VerticalAlignment.Center 
    }; 
    sp1.Children.Insert(0, border); 
} 
+0

真棒...謝謝:) – 2011-03-02 13:14:20

+0

+1代碼片段 – 2011-03-02 13:15:00

0

我覺得rect.VerticalAlignment = VerticalAlignment.Bottom和sp1.Children.Insert(0,RECT)將幫助你。

+0

我試過你的code.It不工作 – 2011-03-01 08:29:38