需要补充的文字为矩形 [英] Need to add text to rectangle

查看:105
本文介绍了需要补充的文字为矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建动态矩形并添加到的StackPanel 。我需要将文本添加到每个矩形。我该怎么做?

I am creating Dynamic Rectangle and adding into StackPanel. I need to add text to each rectangle. How can I do that?

推荐答案

一个矩形没有任何孩子的内容,所以你需要把两个控件内另一个小组,如格:

A Rectangle doesn't have any child content, so you will need to put both controls inside of another panel, such as a grid:

<Grid>
    <Rectangle Stroke="Red" Fill="Blue"/>
    <TextBlock>some text</TextBlock>
</Grid>

您也可以使用边境管制,这将需要一个孩子和周围画一个矩形:

You can also use a Border control, which will take a single child and draw a rectangle around it:

<Border BorderBrush="Red" BorderThickness="1" Background="Blue">
    <TextBlock>some text</TextBlock>
</Border>

您说的动态方块,所以它听起来就像你在代码中这样做。等效C#看起来是这样的:

You say "dynamic rectangle", so it sounds like you are doing this in code. The equivalent C# would look something like this:

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:

But if you want a dynamic list of rectangles, you should probably use an 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为每一个与设置在对象上的文本属性的文本。

If you set the DataContext to a list of objects, this XAML will create a Border with a TextBlock for each one with the text set to the Text property on the object.

这篇关于需要补充的文字为矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆