Qua*_*ter 33
Rectangle没有任何子内容,因此您需要将两个控件放在另一个面板中,例如网格:
<Grid>
<Rectangle Stroke="Red" Fill="Blue"/>
<TextBlock>some text</TextBlock>
</Grid>
Run Code Online (Sandbox Code Playgroud)
您还可以使用边框控件,它将占用一个子节点并在其周围绘制一个矩形:
<Border BorderBrush="Red" BorderThickness="1" Background="Blue">
<TextBlock>some text</TextBlock>
</Border>
Run Code Online (Sandbox Code Playgroud)
你说"动态矩形",所以听起来你在代码中这样做.等效的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" },
});
Run Code Online (Sandbox Code Playgroud)
但是如果你想要一个动态的矩形列表,你应该使用ItemsControl:
<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Red" BorderThickness="1" Background="Blue">
<TextBlock Text="{Binding Text}"/>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Run Code Online (Sandbox Code Playgroud)
如果将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);
Run Code Online (Sandbox Code Playgroud)