需要将文本添加到矩形

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

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

   some text  

您还可以使用Border控件,它将占用一个子节点并在其周围绘制一个矩形:

  some text  

你说“动态矩形”,所以听起来你在代码中这样做。 等效的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设置为对象列表,则此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 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); 

您需要向StackPanel添加文本控件,例如Label或TextBlock 。