2010-08-29 122 views

回答

30

一個Rectangle沒有任何孩子的內容,所以你需要把雙方的控制另一個小組的內部,如網格:

<Grid> 
    <Rectangle Stroke="Red" Fill="Blue"/> 
    <TextBlock>some text</TextBlock> 
</Grid> 

你也可以使用一個邊境管制,這將需要一個孩子,並繪製一個矩形周圍:

<Border BorderBrush="Red" BorderThickness="1" Background="Blue"> 
    <TextBlock>some text</TextBlock> 
</Border> 

你說「動態方塊」,所以它聽起來像你在代碼實現這一點。等效C#會是這個樣子:

var grid = new Grid(); 
grid.Children.Add(new Rectangle() { Stroke = Brushes.Red, Fill = Brushes.Blue }); 
grid.Children.Add(new TextBlock() { Text = "some text" }); 
panel.Children.Add(grid); 
// or 
panel.Children.Add(new Border() 
{ 
    BorderBrush = Brushes.Red, 
    BorderThickness = new Thickness(1), 
    Background = Brushes.Blue, 
    Child = new TextBlock() { Text = "some text" }, 
}); 

但是如果你想長方形的動態列表,你應該使用一個ItemsControl:如果您設置的DataContext對象的列表

<ItemsControl ItemsSource="{Binding}"> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
      <Border BorderBrush="Red" BorderThickness="1" Background="Blue"> 
       <TextBlock Text="{Binding Text}"/> 
      </Border> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 

,此XAML將爲每個文本塊創建一個帶有TextBlock的邊框,並將該文本設置爲該對象上的Text屬性。

+1

你能否提供一些代碼片段來綁定Itemcontrol的Datacontext。 – Lalchand 2010-08-29 17:31:59

1

您需要爲您的StackPanel添加文本控件,如LabelTextBlock

+0

我需要在Rectangle中添加文本。如何將標籤添加到矩形中。 – Lalchand 2010-08-29 16:15:33

2

首先你可以做到這一點,但不是通過添加控件。對於高速硬件渲染,有一個很好的理由來做到這一點。您可以從UI元素中創建一個特殊的畫筆,該畫筆可以在硬件中自行緩存,並使用此硬件填充矩形,並且速度非常快。我只會顯示代碼背後,因爲它是我現有的示例

Rectangle r = new Rectangle(); 
r.Stroke = Brushes.Blue; 
r.StrokeThickness = 5; 
r.SetValue(Grid.ColumnProperty, 1); 
r.VerticalAlignment = VerticalAlignment.Top; 
r.HorizontalAlignment = HorizontalAlignment.Left; 
r.Margin = new Thickness(0); 
r.Width = 200; 
r.Height = 200; 
r.RenderTransform = new TranslateTransform(100, 100); 
TextBlock TB = new TextBlock(); 
TB.Text = "Some Text to fill"; 
//The next two magical lines create a special brush that contains a bitmap rendering of the UI element that can then be used like any other brush and its in hardware and is almost the text book example for utilizing all hardware rending performances in WPF unleashed 4.5 
BitmapCacheBrush bcb = new BitmapCacheBrush(TB); 
r.Fill = bcb; 
MyCanvas.Children.Add(r);