【问题标题】:WPF: How to limit width of all columns combined in DataGrid?WPF:如何限制 DataGrid 中组合的所有列的宽度?
【发布时间】:2012-10-30 15:58:36
【问题描述】:

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

当我点击一个按钮时,DataGrid 中的数据被导出到一个 pdf 文件中。

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

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

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

【问题讨论】:

    标签: c# .net wpf


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2017-12-05
      • 2015-03-20
      • 2011-11-29
      • 2012-06-06
      • 1970-01-01
      • 2013-07-26
      • 2011-03-25
      • 2011-11-02
      • 1970-01-01
      相关资源
      最近更新 更多