2015-04-30 103 views
0

我寫這個方法現在的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) }); 
    } 

我終於預告三個函數之間的區別僅僅是網格被填充的東西:一個List對象的通用列表(有時候,Viewbox Stretch屬性被設置爲什麼)。

我想編寫一個通用的方法來代替這三個(和所有未來的)方法,我有一個想法如何做到這一點?

回答

-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) }); 
    } 

你要知道,不是每個人都希望自己的孩子扔進箱,並很有可能在(或者已經接近的東西已經完成了),但我想我想分享一下。