如何用控件编程创建一个xaml面板 [英] How to programatically create a xaml panel with controls

查看:172
本文介绍了如何用控件编程创建一个xaml面板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在包含重复元素的当前文档中以编程方式创建新面板?
例如,当窗口加载我有一个网格(一行)与三个文本字段,Fname01,Lname01和DOB01,我想有一个按钮,当点击将附加一个新行到网格与三新字段(Fname02,Lname02和DOB02)。每次点击按钮(addrow),将创建一个新行。我也有兴趣了解如何在xaml中识别这些字段,这将允许我databind或编程引用创建的字段插入值到数据库等。



提前谢谢,

解决方案

是的。要创建新行,请调用Grid.RowDefinitions.Add:

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

然后创建要在网格中移动的元素,将它们新建,属性,并将它们添加到Grid.Children集合中:

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

现在,您可以通过变量以编程方式引用文本框:

  fname.Text =我是文本框; 

或设置绑定:

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






EDIT: Benny在他的回答中说,如果你想要显示一个数据集合,那么一个ItemsControl绝对是一个更好的方式,而不是通过编程添加到布局网格。我会留下答案,因为它可能仍然与非项目列表的情况相关。


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.

这篇关于如何用控件编程创建一个xaml面板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆