GridViewColumn宽度调整

问题描述:

我的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的列使用控件的完整宽度)?

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

我把这个从How to autosize and right-align GridViewColumn data in WPF?

<Window.Resources> 
    <Style TargetType="ListViewItem"> 
     <Setter Property="HorizontalContentAlignment" Value="Stretch" /> 
    </Style> 
</Window.Resources> 

,帮助你呢?

+0

为我工作!谢谢 – Omer 2013-10-13 10:15:44