Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
455 views
in Technique[技术] by (71.8m points)

user interface - How to add wpf control to particular grid row and cell during runtime?

I have the following grid in my WPF "Window" (yes the class Window);

<Grid Name="RequiredGrid">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="70" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
        </Grid>

Depending on whats passed into the window, I want to add items into this grid one row at a time. Namely, I want to add a Label in the left column and a TextBox in the right column. I believe I know how to add new rows for holding new data by doing the following in the code behind:

RequiredGrid.RowDefinitions.Add(new RowDefinition());

Problem is, after I've created my Label and my TextBox.

Label AttrLabel = new Label();
TextBox AttrTextBox = new TextBox();

I don't really know how to get it into the Window so it gets displayed. I've seen some threads that say, do something like this:

this.Controls.Add(AttrLabel);
this.Controls.Add(AttrTextBox);

There are two problems with this. 1) My Window class doesn't have this "Controls" property or whatever. And 2) This wouldn't help me specify the row and column of each UI item.

Now in XAML, Id be easy to specify the row and column with something like this:

 <Label Grid.Column="0" Grid.Row="0"/>

This defeats the "dynamic-ness" of my intent here though. Does anyone know how I can get my dynamicaly created UI elements to display in my Window and specify which row and column it will show up in the grid.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The Grid.Row and Grid.Column properties are Attached Properties, and as such are not set like normal .net properties. The right way to set them from code is:

Grid.SetRow(someLabel, 0);
Grid.SetColumn(someLabel, 0);

You should be able to do this before or after adding them to the Grid object's Children collection, but setting them before adding the control should prevent any possible flickering.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...