开发者

WPF: Dynamical Label addition in Grid

I have to create a table to display the KEY VALUE kind of thing.

I tried the below code but messed up with overlapping output. I believe, I need to create the Grid RowDefinitions and ColumnDefinitions but not able to achieve it. Please help me.

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>

Code behind:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            AddLabelDynamically();
        }

        private void AddLabelDynamically()
        {
            for (int i = 0; i < 3; i++)
     开发者_JAVA技巧       {
                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);
            }
        }
    }


You have to define Row and Column definitions and assign Rows and Columns to child Controls. Following code does that:

    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);
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜