我现在已经写过这个方法大约3次了,而且我很确定我一段时间不会写这个方法:
public void PopulateField( ) {
this.grdNameField.ColumnDefinitions.Clear( );
this.grdNameField.RowDefinitions.Clear( );
this.grdNameField.Children.Cast<Viewbox>( ).ToList( ).ForEach( VB => VB.Child = null );
this.grdNameField.Children.Clear( );
for ( int x = 0; x < Settings.Default.PlayerCount; x++ ) {
Viewbox VB = new Viewbox( ) { Child = this.PlayerNamers[x], Stretch = Stretch.Uniform };
this.grdNameField.Children.Add( VB );
Grid.SetColumn( VB, x % Math.Max( 3, ( int )( Math.Ceiling( Settings.Default.PlayerCount / 5.0D ) ) ) );
Grid.SetRow( VB, x / Math.Max( 3, ( int )( Math.Ceiling( Settings.Default.PlayerCount / 5.0D ) ) ) );
}
int
ColumnCount = this.grdNameField.Children.Cast<Viewbox>( ).Max( VB => Grid.GetColumn( VB ) ) + 1,
RowCount = this.grdNameField.Children.Cast<Viewbox>( ).Max( VB => Grid.GetRow( VB ) ) + 1;
for ( int x = 0; x < ColumnCount; x++ )
this.grdNameField.ColumnDefinitions.Add( new ColumnDefinition( ) { Width = new GridLength( 1, GridUnitType.Star ) } );
for ( int x = 0; x < RowCount; x++ )
this.grdNameField.RowDefinitions.Add( new RowDefinition( ) { Height = new GridLength( 1, GridUnitType.Star ) } );
}
我终于注意到这三个函数之间的区别仅在于网格的填充:对象列表的通用列表(有时候,Viewbox Stretch属性被设置为什么)。 / p>
我想写一个通用方法来替换这三个(以及将来所有)方法,我知道如何做到这一点......
答案 0 :(得分:-1)
当我输入这个问题时,让我感到震惊的是,除了编写一个处理填充网格的通用方法之外,我还可以做得更远 - 我可以编写一个扩展方法,这就是我所做的:
public static void Populate<T>( this Grid Parent, List<T> Children, Stretch ViewBoxStretch ) where T : UIElement {
Parent.ColumnDefinitions.Clear( );
Parent.RowDefinitions.Clear( );
Parent.Children.Cast<Viewbox>( ).ToList( ).ForEach( VB => VB.Child = null );
Parent.Children.Clear( );
for ( int x = 0; x < Children.Count; x++ ) {
Viewbox VB = new Viewbox( ) { Child = Children[x], Stretch = ViewBoxStretch };
Parent.Children.Add( VB );
Grid.SetColumn( VB, x % Math.Max( 3, ( int )( Math.Ceiling( Children.Count / 5.0D ) ) ) );
Grid.SetRow( VB, x / Math.Max( 3, ( int )( Math.Ceiling( Children.Count / 5.0D ) ) ) );
}
int
ColumnCount = Parent.Children.Cast<Viewbox>( ).Max( VB => Grid.GetColumn( VB ) ) + 1,
RowCount = Parent.Children.Cast<Viewbox>( ).Max( VB => Grid.GetRow( VB ) ) + 1;
for ( int x = 0; x < ColumnCount; x++ )
Parent.ColumnDefinitions.Add( new ColumnDefinition( ) { Width = new GridLength( 1, GridUnitType.Star ) } );
for ( int x = 0; x < RowCount; x++ )
Parent.RowDefinitions.Add( new RowDefinition( ) { Height = new GridLength( 1, GridUnitType.Star ) } );
}
请注意,并非所有人都希望将自己的孩子扔进盒子里,而且很可能(或者已经完成了足够近的事情),但我想我想分享一下。