需要将文本添加到矩形

时间:2010-08-29 16:09:08

标签: c# wpf

我正在创建动态矩形并添加到StackPanel。我需要为每个矩形添加文本。我怎么能这样做?

3 个答案:

答案 0 :(得分:33)

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:

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

如果将DataContext设置为对象列表,则此XAML将为每个对象创建一个带有TextBlock的边框,并将文本设置为对象的Text属性。

答案 1 :(得分:4)

首先,您可以执行此操作,但不能添加控件。对于高速硬件渲染,有一个很好的理由这样做。您可以从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);

答案 2 :(得分:1)

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