WPF:Grid中的动态标签添加

时间:2010-12-13 13:12:01

标签: c# wpf

我必须创建一个来显示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);
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

您必须定义行和列定义并将子行和列分配给子控件。以下代码执行:

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