有没有比网格更好的方法来排列 WPF 中的控件?
我根据这个问题 Grid vs Stackpanel 中定义的适当性定义使用网格。但是,在使用网格时,您必须在网格中显式定义其中的控件位置。当必须重新排序控件或向网格添加新控件时,这会变得很痛苦。以提供的代码为例,有没有办法让文本和文本框的行和列对齐,同时便于以后修改或扩展?
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="7*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Text="Value One:" Grid.Row="0" Grid.Column="0"/>
<TextBox x:Name="TextBoxOne" Grid.Row="0" Grid.Column="1"/>
<TextBlock Text="Value Two:" Grid.Row="1" Grid.Column="0"/>
<TextBox x:Name="TextBoxTwo" Grid.Row="1" Grid.Column="1"/>
<TextBlock Text="Value Three:" Grid.Row="2" Grid.Column="0"/>
<TextBox x:Name="TextBoxThree" Grid.Row="2" Grid.Column="1"/>
</Grid>
I am using a grid by the definition of appropriateness defined in this question Grid vs Stackpanel. However when working with grids you have to define the controls position inside them explicitly in the grid. This becomes a pain when having to reorder controls or when adding a new control to the grid. With the code provided as an example, is there a way to get the rows and columns for the text and text boxes to line up while being easy to modify or expand later?
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="7*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Text="Value One:" Grid.Row="0" Grid.Column="0"/>
<TextBox x:Name="TextBoxOne" Grid.Row="0" Grid.Column="1"/>
<TextBlock Text="Value Two:" Grid.Row="1" Grid.Column="0"/>
<TextBox x:Name="TextBoxTwo" Grid.Row="1" Grid.Column="1"/>
<TextBlock Text="Value Three:" Grid.Row="2" Grid.Column="0"/>
<TextBox x:Name="TextBoxThree" Grid.Row="2" Grid.Column="1"/>
</Grid>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我编写了一个使用的自定义控件,这使得执行此操作变得非常容易,但在创建它之前,我通常使用这种东西:
这允许轻松地从 ItemsControl 添加/删除项目,或者更好的是,数据绑定。
如果您更喜欢在网格上自动调整大小而不是星形调整大小(3* 和 7*),则可以通过在
ItemsControl
和上设置
。IsSharedSizeScope
来使用共享大小调整范围第一个ColumnDefinition
上的 >SharedSizeGroup另一个选择是 GridView,但我发现它更难以用于此目的。
I wrote a custom control I use that makes it extremely easy to do this, but before I created it I generally used this sort of thing:
This allows easy add/remove of items from the ItemsControl, or better yet, data binding.
If you prefer auto-sizing on the grid rather than star sizing (3* and 7*) you can use a shared sizing scope by setting
IsSharedSizeScope
on theItemsControl
andSharedSizeGroup
on the firstColumnDefinition
.Another option is
GridView
, but I find it more difficult to use for this purpose.