2012-01-31 152 views
5

我的UI:GridViewColumn寬度調整

<ListView Name="persons" SelectionChanged="persons_SelectionChanged"> 
     <ListView.View> 
      <GridView AllowsColumnReorder="False"> 
       <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" Width="auto"/> 
       <GridViewColumn Header="Age" DisplayMemberBinding="{Binding Age}" Width="auto"/> 
      </GridView> 
     </ListView.View> 
    </ListView> 

我的用戶界面的代碼隱藏:

internal void Update(IEnumerable<Person> pers) 
    { 
     this.persons.ItemsSource = null; 
     this.persons.ItemsSource = pers; 
     UpdateLayout(); 
    } 

我的實體:

class Person 
{ 
    public string Name { get; set; } 
    public int Age { get; set; } 
} 

的GridViewColumns有GridViewColumn標頭的寬度。即使我打電話更新()與人名長。該列不會調整大小。我怎麼能自動調整「名稱」列的大小(當我稱爲更新)的最長名稱的長度,但不超過一個值x(我想指定列的最大寬度) ?

b)我怎樣才能指定「Age」-Column填充控件結尾的空間(以便GridView的列使用控件的完整寬度)?

回答

6

GridView不會自動調整大小。

要調整列可以

foreach (GridViewColumn c in gv.Columns) 
    { 
     // Code below was found in GridViewColumnHeader.OnGripperDoubleClicked() event handler (using Reflector) 
     // i.e. it is the same code that is executed when the gripper is double clicked 
     // if (adjustAllColumns || App.StaticGabeLib.FieldDefsGrid[colNum].DispGrid) 
     if (double.IsNaN(c.Width)) 
     { 
      c.Width = c.ActualWidth; 
     } 
     c.Width = double.NaN; 
    } 

至於大小,最後以填補我區與轉換器做到這一點。我不認爲這個轉換器完全符合你的需求,但它應該讓你開始。

<GridViewColumn Width="{Binding ElementName=lvCurDocFields, Path=ActualWidth, Converter={StaticResource widthConverter}, ConverterParameter=100}"> 


    [ValueConversion(typeof(double), typeof(double))] 
    public class WidthConverter : IValueConverter 
    { 
     public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
     { 
      // value is the total width available 
      double otherWidth; 
      try 
      { 
       otherWidth = System.Convert.ToDouble(parameter); 
      } 
      catch 
      { 
       otherWidth = 100; 
      } 
      if (otherWidth < 0) otherWidth = 0; 

      double width = (double)value - otherWidth; 
      if (width < 0) width = 0; 
      return width; // columnsCount; 

     } 

     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
     { 
      throw new NotImplementedException(); 
     } 
    } 

GridView很快,但它需要一點嬰兒坐。

+0

我知道這已經很老了,但我想強調一下'ColumnWidth'修復程序的時間有多重要,並且在正確應用時效果很好。確保GridView容器已加載並可見。我有一個非常討厭的組合,將一個GridView放置在一個擴展器中,而這個擴展器又是虛擬化父控件的一部分。意思是,在離屏時調整大小會產生零寬度,並且當模板被回收用於不同的數據時項目可能會改變。現在我對我的解決方案感到滿意。 – grek40 2016-11-02 18:05:14