简单的解决方案是通过简单地设置 ColumnWidth 属性来使 DataGrid 对其列使用星型大小,如下所示:
<DataGrid Width="800" ColumnWidth="*" />
然而,问题在于这使得所有列都一样宽,这可能是不希望的。
所以我要做的是首先像现在一样以默认方式创建所有列,然后将每列设置为星大小。这样,可以为新宽度计算一个值,使列保持其初始大小。
我写了一小段代码来说明我的意思..
XAML
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication2"
Title="MainWindow" Height="350" Width="850">
<StackPanel>
<DataGrid x:Name="dgTest" Width="800" Loaded="dgTest_Loaded" />
</StackPanel>
</Window>
代码隐藏
public partial class MainWindow : Window
{
public class Test
{
public string P1 { get; set; }
public string P2 { get; set; }
public string P3 { get; set; }
}
public MainWindow()
{
InitializeComponent();
var t = new List<Test>(new[] {
new Test{ P1="på,dsl", P2="234234", P3="asdasdasd"},
new Test{ P1="asasaspå,dsl", P2="23sadasd asf afasdasdasd4234", P3="asdasdasd" },
new Test{ P1="på,ds1231l", P2="234", P3="1ddsdasd" },
});
dgTest.ItemsSource = t;
}
private void dgTest_Loaded(object sender, RoutedEventArgs e)
{
//Make the columns use starsizing so their combined width
//can't be bigger than the actual datagrid that contains them.
foreach (var column in dgTest.Columns)
{
var starSize = column.ActualWidth / dgTest.ActualWidth;
column.Width = new DataGridLength(starSize, DataGridLengthUnitType.Star);
}
}
}