我正在创建动态矩形并将其添加到StackPanel
中。我需要为每个矩形添加文本。我怎样才能做到这一点?需要将文字添加到矩形
12
A
回答
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
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);
相关问题
- 1. d3将文本添加到SVG矩形
- 2. D3将文本添加到矩形中
- 3. GIS:需要将数据添加到一个形状文件
- 4. 将增长过渡添加到矩形
- 5. 将JButton和矩形添加到JFrame
- 6. 将矩形添加到箭袋图
- 7. 如何将矩形添加到PathFigure WPF
- 8. 将矩形添加到图像
- 9. 将颜色添加到矩形
- 10. C#WinForms将名称添加到矩形?
- 11. 如何将mouseListener添加到graphics2D矩形
- 12. 关于在Java中将矩形添加到矩形的建议
- 13. 将矩形添加到列表中并显示矩形
- 14. 用户将文字添加到形状
- 15. 如何在Android中将矩形形状添加到矩形形状
- 16. Java FileHandler将不需要的数字添加到文件名
- 17. 我需要将文本字段中的值添加到android
- 18. 旋转矩形需要
- 19. D3条形图需要特别添加箭头和文字吧
- 20. 如何将文本添加到这些矩形?
- 21. 如何将文本添加到pygame矩形中
- 22. 将标签或文本添加到3D矩形java
- 23. 使用itext5将文本添加到PDF中的矩形
- 24. PowerPoint宏 - 需要添加矩形和注释到每个幻灯片
- 25. 需要将javascript添加到heroku
- 26. 我需要将observablecollection添加到observablecollection。
- 27. 需要什么将knockout.js添加到HotTowel?
- 28. 需要将minSize添加到fitText
- 29. 如何将阴影添加到dc.js条形图矩形
- 30. 如何将4个按钮添加到矩形/圆形
你能否提供一些代码片段来绑定Itemcontrol的Datacontext。 – Lalchand 2010-08-29 17:31:59