2010-08-29 83 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);