简体   繁体   English

添加“动态”控件的最佳方法?

[英]Best way to add “dynamic” controls?

My program will prompt the user for a number, ie 25. The program will then start the "main form" with 25 controls (textbox). 我的程序将提示用户输入数字,即25。然后,程序将使用25个控件(文本框)启动“主窗体”。 The 25 (or whatever number) of textboxes (or whatever control) will need to be formatted evenly. 25个(或任意数量)的文本框(或任意控件)将需要均匀设置格式。 I will also need to be able to retrieve the text (or another property if I use another control) in order, from left to right and up to down. 我还需要能够按从左到右,从上到下的顺序检索文本(如果使用其他控件,则可以检索另一个属性)。 What is the best method of approaching this? 解决此问题的最佳方法是什么?

Using WPF MVVM. 使用WPF MVVM。 In a .XAML file, create a DataTemplate with the DataType of a ViewModel that will provide the binding for your TextBox s, lets call this the TextboxViewModel . .XAML文件中,使用ViewModel的DataType创建一个DataTemplate ,它将为您的TextBox提供绑定,让我们将其TextboxViewModel Then using a ItemsControl element with an ItemsSource of TextboxViewModel . 然后将ItemsControl元素与TextboxViewModelItemsSource TextboxViewModel You'll be able to instantiate as many TextBox s as you want and be able to get the result by browsing through your list of TextboxViewModel . 您将可以实例化任意多个TextBox ,并可以通过浏览TextboxViewModel列表来获取结果。

Supposing you are using Windows Forms here. 假设您在这里使用Windows窗体。 Dynamically create the X controls and add them to the Controls collection of your form. 动态创建X控件并将其添加到窗体的Controls集合。 To ease the access to them you can store their reference in a List and set some event handlers too, depending on your needs. 为了简化对它们的访问,您可以根据需要在列表中存储它们的引用,并设置一些事件处理程序。 You just need to calculate their positions while you add them. 添加它们时,您只需要计算它们的位置即可。

If WinForms, this is exactly what the FlowLayoutPanel is for. 如果是WinForms,这正是FlowLayoutPanel的用途。 Just add the controls to it and they will arrange themselves automatically, wrapping down to the next row as needed. 只需向其中添加控件,它们就会自动进行排列,并根据需要包装到下一行。 As Mihai already suggested, you could also keep reference to those controls in a List. 正如Mihai已经建议的那样,您还可以在列表中继续引用这些控件。

Another option would be to use a TableLayoutPanel . 另一种选择是使用TableLayoutPanel It's a little more difficult to learn and use, but is much more flexible and powerful. 学习和使用起来有点困难,但更加灵活和强大。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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