WPF:Grid中的动态标签添加

我必须创建一个表来显示KEY VALUE类的东西。 我尝试了下面的代码,但搞砸了重叠输出。我相信,我需要创建Grid RowDefinitions和ColumnDefinitions但不能实现它。请帮我。 XAML:
<Window x:Class="GrideLabel.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid  Name="LabelGrid"></Grid>
</Window>
代码背后:
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            AddLabelDynamically();
        }

        private void AddLabelDynamically()
        {
            for (int i = 0; i < 3; i++)
            {
                Label nameLabel = new Label(); nameLabel.Content = "KEY :"+i.ToString();
                Label dataLabel = new Label(); dataLabel.Content = "VALUE :"+i.ToString();
                //I want to creatre the Seperate coloum and row to  display KEY
                // VALUE Pair distinctly
                this.LabelGrid.Children.Add(nameLabel);
                this.LabelGrid.Children.Add(dataLabel);
            }
        }
    }
    
已邀请:
您必须定义行和列定义,并将行和列分配给子控件。以下代码执行此操作:
    private void AddLabelDynamically()
    {
        this.LabelGrid.ColumnDefinitions.Clear();
        this.LabelGrid.RowDefinitions.Clear();

        this.LabelGrid.ColumnDefinitions.Add(new ColumnDefinition());
        this.LabelGrid.ColumnDefinitions.Add(new ColumnDefinition());

        for (int i = 0; i < 3; i++)
        {
            this.LabelGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

            Label nameLabel = new Label(); nameLabel.Content = "KEY :" + i.ToString();
            Label dataLabel = new Label(); dataLabel.Content = "VALUE :" + i.ToString();

            Grid.SetRow(nameLabel, i);
            Grid.SetRow(dataLabel, i);

            Grid.SetColumn(nameLabel, 0);
            Grid.SetColumn(dataLabel, 1);

            //I want to creatre the Seperate coloum and row to  display KEY
            // VALUE Pair distinctly
            this.LabelGrid.Children.Add(nameLabel);
            this.LabelGrid.Children.Add(dataLabel);
        }
    }
    

要回复问题请先登录注册