如何使用代码将标签添加到C#WPF网格? [英] How to add a Label to a C# WPF Grid with code?

查看:105
本文介绍了如何使用代码将标签添加到C#WPF网格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我只是第一门课程的学生.
我正在尝试创建一个Labels数组,并在运行时在设计器中显示它们.
(将标签笔直放置在设计器中)

这是我当前的代码:

Hi,
I''m only a student at the end of my first course..
I''m trying to create an array of Labels and to show them in the designer during run time.
(instade of placing a label straight in the designer)

this is my current code:

public MainWindow() // THIS IS THE LINE I REMOVED FROM XMAL -                                   // AND  I'D LIKE TO RE-WRITE IT IN CODE @ [MAIN]
        {       // Label Height="28" HorizontalAlignment="Left" Margin="221,98,0,0" Name="lblScoreD6" VerticalAlignment="Top" Width="100" Content="0" />
            InitializeComponent();
            Label[] scoresLabelArr = new Label[5];
            int location = 98;
            for (int i = 0; i < scoresLabelArr.Length; i++)
            {
                scoresLabelArr[i] = new Label();
                scoresLabelArr[i].Height = 28;
                scoresLabelArr[i].Width = 100;
                scoresLabelArr[i].HorizontalAlignment = HorizontalAlignment.Left;
                scoresLabelArr[i].VerticalAlignment = VerticalAlignment.Top;
                scoresLabelArr[i].Content = 0;
                scoresLabelArr[i].Margin = new Thickness(211, location, 0, 0);
                location += 34;
// I MISS SOMETHING HERE *** IN ORDER TO VIEW THOSE 5 LABELS I'VE CREATED ABOVE DURING THE RUN TIME - please advise :)




            }

推荐答案

for (int i = 0; i < scoresLabelArr.Length; i++)
{
    grid1.Children.Add(scoresLabelArr[i]);
}



或者,您可以通过以下方式进行操作:



Or, you can do it this way:

int location = 98;
for (int i = 1; i <= 5; i++)
{
    Label label = new Label();
    label.Height = 28;
    label.Width = 100;
    label.HorizontalAlignment = HorizontalAlignment.Left;
    label.VerticalAlignment = VerticalAlignment.Top;
    label.Content = 0;
    label.Margin = new Thickness(211, location, 0, 0);
    grid1.Children.Add(label);
    location += 34;
}


这篇关于如何使用代码将标签添加到C#WPF网格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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