简体   繁体   中英

How to programatically create a xaml panel with controls

Is it possible to programatically create a new panel within a current document that contains duplicate elements? For example when the window loads I have a grid (one row) with three text fields, Fname01, Lname01, and DOB01, I would like to have a button that when clicked would append a new row to the grid with three new fields (Fname02, Lname02, and DOB02). Each time the button is clicked (addrow) a new row would be created. I am also interested to learn how these fields are identified within the xaml that would allow me to databind or programatically reference the created fields for insertion of the values into a database etc.

Thank you in advance,

Yes. To create the new row, call Grid.RowDefinitions.Add:

myGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });

Then to create the elements to go in the grid, new them up, set the row and column attached properties, and add them to the Grid.Children collection:

int rowIndex = myGrid.Rows.Count - 1;  // or whatever
TextBox fname = new TextBox();
Grid.SetRow(fname, rowIndex);
Grid.SetColumn(fname, 0);
myGrid.Children.Add(fname);

You can now programmatically refer to the text box through the variable:

fname.Text = "I'm a text box";

or set bindings on it:

fname.SetBinding(TextProperty, new Binding { Source = mySource, Path = new PropertyPath("FirstName") });

EDIT: As Benny says in his answer, if you are wanting to display a collection of data, then an ItemsControl is definitely a better way to go than programmatically adding to a layout Grid. I'll leave the answer, though, as it may still be relevant to non-items-list scenarios.

You should use a ListBox (or ListView) or a DataGrid. A normal Grid is for layout only, not for managing collections of data.

If you use a ListBox, you can create a DataTemplate for your data object, which the ListBox will use to display the object. In that data template, create the 3-column grid to hold the editing controls, and bind those controls to your data object's properties. For examples and detailed info on DataTemplates and data binding, just search the web for it. There are tons of examples out there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM