动态创建的标签相互重叠

dynamically created labels overlap each other

我想创建一个个标签。我有一个要添加标签的网格名称 WordTemplateLayout。在调用 InitializeComponent() 之后,我将它们动态添加到 wpf window 构造函数中。这是创建标签的方法:

private void CreateWordTemplate()
        {
            IList<char> template = CurrentGame.Template;
            double widthPerBox = WordTemplateLayout.Width / template.Count;
            //template.Count being a number, irrelevant to the question 
            for (int i = 0; i < template.Count; i++)
            {
                var templateVisual = new Label();
                templateVisual.Name = "c" +  i;
                templateVisual.Width = widthPerBox;
                templateVisual.Height = WordTemplateLayout.Height;
                templateVisual.Background = new SolidColorBrush(Colors.Aqua);
                WordTemplateLayout.Children.Add(templateVisual);
            }
        }

问题是,实际上附加的是标签不是一个接一个地排列,而是相互重叠: The aqua box is all the labels overlap each other

所以我要问的是,如何让标签(水平)排列而不是重叠?

正如其他人所指出的,您最好使用 StackPanel,或者学习如何使用视图模型和数据绑定。话虽如此,为了回答您的直接问题,您可以按照以下方式以编程方式进行。

**注意:忽略我传递给方法的 5,而是使用您的 template.Count。这只是为了让它在我这边工作。

        public MainWindow()
        {
            InitializeComponent();
            CreateGridLayout(5);
            CreateWordTemplate(5);
        }

        // Define the Grid layout
        // If you want the labels to follow one another horizontally, define columns.  
        // If you want them stacked vertically, instead define rows.
        private void CreateGridLayout(int count)
        {
            for (int i = 0; i < count; i++)
            {
                WordTemplateLayout.ColumnDefinitions.Add(new ColumnDefinition());
            }
        }

        private void CreateWordTemplate(int count)
        {
            double widthPerBox = WordTemplateLayout.Width / 5;
            for (int i = 0; i < 5; i++)
            {
                var templateVisual = new Label();
                templateVisual.SetValue(Grid.ColumnProperty, i); // SET YOUR COLUMN HERE!
                templateVisual.Name = "c" + i;
                templateVisual.Width = widthPerBox;
                templateVisual.Height = WordTemplateLayout.Height;
                templateVisual.Background = new SolidColorBrush(Colors.Aqua);
                templateVisual.Content = templateVisual.Name;                
                WordTemplateLayout.Children.Add(templateVisual);
            }
        }
  1. 您需要使用其他布局,以便新元素按正常顺序排列。试试 stackPanel。
  2. 您可以使用网格并给每个新标签 Row=index。
  3. 你可以给每个新的标签留边距,比如newLabel。margin-top = index*50