C# 需要将文本添加到矩形中

C# 需要将文本添加到矩形中,c#,wpf,C#,Wpf,我正在创建动态矩形并将其添加到StackPanel。我需要在每个矩形中添加文本。如何操作?您需要将文本控件添加到StackPanel中,例如或。矩形没有任何子内容,因此您需要将这两个控件放在另一个面板中,例如网格: <Grid> <Rectangle Stroke="Red" Fill="Blue"/> <TextBlock>some text</TextBlock> </Grid> 但是,如果您想要一个动态的矩形列表

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

您需要将文本控件添加到StackPanel中,例如或。

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

<Grid>
    <Rectangle Stroke="Red" Fill="Blue"/>
    <TextBlock>some text</TextBlock>
</Grid>
但是,如果您想要一个动态的矩形列表,您可能应该使用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属性

首先,您可以这样做,但不能通过添加控件。对于高速硬件渲染来说,这样做有很好的理由。您可以从缓存在硬件中的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);

我需要在矩形中添加文本。如何将标签添加到矩形中。请提供一些绑定Itemcontrol的Datacontext的代码片段。
<ItemsControl ItemsSource="{Binding}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Border BorderBrush="Red" BorderThickness="1" Background="Blue">
                <TextBlock Text="{Binding Text}"/>
            </Border>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
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);