WPF:如何限制DataGrid中所有列的宽度?

时间:2012-10-30 15:58:36

标签: c# .net wpf

我有一个DataGrid,它从sql表中获取数据。我已将AutoGenerateColumns设置为true。

单击按钮时,DataGrid中的数据将导出为pdf文件。

但是,当DataGrid中所有列的宽度大于约800时,表格大于pdf中的页面。

我已将DataGrid的MaxWidth-Property设置为800.当我调整列的大小时,我可以将光标拖到DataGrid之外,然后会出现水平滚动条。

有没有办法将所有列的最大大小限制为800,这样我就无法使列大于DataGrid?

1 个答案:

答案 0 :(得分:2)

简单的解决方案是通过简单地设置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);
        }
    }
}