需要向矩形添加文本

15

我正在创建动态矩形并将其添加到 StackPanel 中。我需要在每个矩形中添加文本。我该如何实现?

3个回答

35

矩形不包含任何子内容,因此您需要将两个控件放在另一个面板中,例如网格:

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

你也可以使用边框控件(Border control),它将接受单个子元素并在其周围绘制一个矩形:

<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:

<ItemsControl ItemsSource="{Binding}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Border BorderBrush="Red" BorderThickness="1" Background="Blue">
                <TextBlock Text="{Binding Text}"/>
            </Border>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
如果将DataContext设置为对象列表,则此XAML将创建一个Border,其中每个对象都有一个TextBlock,并将文本设置为对象上的Text属性。

2
请问您能否提供一些绑定ItemControl数据上下文的代码片段? - Lalchand

6

首先,您可以通过添加控件来实现此操作,但这并不是最好的方法。为了获得高速硬件渲染,您可以从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 it's 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);

1
您需要向 StackPanel 添加一个文本控件,例如 LabelTextBlock

1
我需要在矩形内添加文本。如何将标签添加到矩形中? - Lalchand

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接