如何使datagrid自动调整的宽度为父控件宽度

时间:2014-06-17 14:10:34

标签: wpf xaml wpfdatagrid

在网格中有一个DataGrid,我想让datagrid width和datagrid列自动适合父控件。

因此,如果用户决定增加窗口宽度,如何使网格宽度及其列也增加?

<Window x:Class="AME.WpfBidouille.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <DataGrid>           
            <DataGrid.Columns>
                <DataGridTextColumn Header="Publication date"/>
                <DataGridTextColumn Header="A very large field to be displayed"/>
                <DataGridTextColumn Header="N° Omega" />
                <DataGridTextColumn Header="Crée le" />
                <DataGridTextColumn Header="Login" />
                <DataGridTextColumn Header="Demandeur" />
                <DataGridTextColumn Header="Type" />
                <DataGridTextColumn Header="Status" />
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

2 个答案:

答案 0 :(得分:3)

将每个列的Width设置为"*"

    <DataGrid>           
        <DataGrid.Columns>
            <DataGridTextColumn Width="*" Header="Publication date"/>
            <DataGridTextColumn Width="*" Header="A very large field to be displayed"/>
            <DataGridTextColumn Width="*" Header="N° Omega" />
            <DataGridTextColumn Width="*" Header="Crée le" />
            <DataGridTextColumn Width="*" Header="Login" />
            <DataGridTextColumn Width="*" Header="Demandeur" />
            <DataGridTextColumn Width="*" Header="Type" />
            <DataGridTextColumn Width="*" Header="Status" />
        </DataGrid.Columns>
    </DataGrid>

答案 1 :(得分:0)

另一种方法是创建一个样式并使用它将其应用到DataGrid

    <Style x:Key="DynamicGridColumns" TargetType="DataGrid">
        <Setter Property="ColumnWidth" Value="*" />
    </Style>

    <DataGrid Style="{StaticResource DynamicGridColumns}">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Publication date"/>
            <DataGridTextColumn Header="A very large field to be displayed"/>
            <DataGridTextColumn Header="N° Omega" />
            <DataGridTextColumn Header="Crée le" />
            <DataGridTextColumn Header="Login" />
            <DataGridTextColumn Header="Demandeur" />
            <DataGridTextColumn Header="Type" />
            <DataGridTextColumn Header="Status" />
        </DataGrid.Columns>
    </DataGrid>