0xD*_*EEF 5 .net c# wpf xaml gridview
我的UI:
<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>
Run Code Online (Sandbox Code Playgroud)
我的UI的Codebehind:
internal void Update(IEnumerable<Person> pers)
{
this.persons.ItemsSource = null;
this.persons.ItemsSource = pers;
UpdateLayout();
}
Run Code Online (Sandbox Code Playgroud)
我的实体:
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
GridViewColumns具有GridViewColumn-Header的宽度.即使我使用长名称的人调用Update().列不会调整大小.
a)如何自动调整"名称"列(当我调用更新时)到最长名称的长度,但不长于值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;
}
Run Code Online (Sandbox Code Playgroud)
至于确定最后填充区域的大小,我使用转换器.我不认为这个转换器完全符合您的需要,但它应该让您开始.
<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();
}
}
Run Code Online (Sandbox Code Playgroud)
GridView很快但需要一点宝宝坐着.